2015-02-10 47 views
0

我有下面的示例JSON:JSON解析不 - 类型错误

{ 
"findItemsByKeywordsResponse":[ 
    { 
    "ack":[ 
     "Success" 
    ], 
    "version":[ 
     "1.13.0" 
    ], 
    "timestamp":[ 
     "2015-02-10T18:12:21.785Z" 
    ], 
    "searchResult":[ 
     { 
      "@count":"100", 
      "item":[ 
       { 
       "itemId":[ 
        "371250980931" 
       ], 
       "title":[ etc etc... 

我想如下解析它:

function _cb_findItemsByKeywords(root) { 
    var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || []; 
    etc etc... 
} 

但得到以下错误:

TypeError: root.findItemsByKeywordsResponse is undefined 
    var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || []; 
    ----^ 

任何想法我做错了什么?

+1

你的代码不是关于解析,而是访问推测的解析元素。 – 2015-02-10 18:29:41

+0

是的,这是正确的,解析是我能想到的最近描述 – 2015-02-10 18:30:52

+1

只是一个想法:你检查了你的根变量的内容:'alert(JSON.stringify(root))'?这可能表明您正在使用您认为的不同的json。 – szpetip 2015-02-10 18:33:47

回答

2

你需要分析根

function _cb_findItemsByKeywords(root) { 
    root = JSON.parse(root); 
    var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || []; 
    etc etc... 
} 

一个JSON只是一个字符串到Javascript和你需要把它解析的对象。