2015-02-10 31 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和你需要把它解析的對象。