2011-07-15 130 views
0

我有這個我試圖訪問json值,但它甚至不產生任何警報。問題是什麼?訪問JSON字符串值

我的JSON

{ 
"response": [ 
{ 
    "id": "0", 
    "elementName": "osname", 
    "isEqual": true, 
    "isPrasentinXml1": true, 
    "isPrasentinXml2": true, 
    "attribute": [ 
    { 
     "name": "osname", 
     "firstValue": "Linux\u000a", 
     "secondValue": "SunOs\u000a" 
    } 
    ] 
}, 
{ 
    "id": "1", 
    "elementName": "hostname", 
    "isEqual": false, 
    "isPrasentinXml1": true, 
    "isPrasentinXml2": true, 
    "attribute": [ 
    { 
     "name": "hostname", 
     "firstValue": "estilo\u000a", 
     "secondValue": "buckeye.informatica.com\u000a" 
    } 
    ] 
} 
] 
} 

我想獲取Linux\u000aSunOs\u000a,所以我寫了

alert(compareData.response[0].attribute[0].firstValue+", "+compareData.response[0].attribute[0].secondValue); 

注:compareData是我的數據是實際的代碼

回答

5

你的錯誤是,你有你的JSON引號,它被視爲一個字符串。此外,您忘記在第二個alert中用jsonobj替換compareData變量名稱。嘗試下面的小提琴,它似乎是你想要的。

的jsfiddle:​​

編輯:

如果你的JSON真的用字符串表示看看邁克爾Sagalovich解決方案。

+0

+1之前沒有注意到您的答案。 –

0

據我看到它的小提琴,你的對象是字符串。你首先需要將它解析成一個對象。 compareData = JSON.parse(compareData)可能有幫助(我認爲大多數瀏覽器都支持JSON.parse)。 jQuery也有解析器:$.parseJSON(compareData)

0

您的語法。此作品:

var jsonobj = { 
    "response": [ 
     { 
     "id": "0", 
     "elementName": "osname", 
     "isEqual": true, 
     "isPrasentinXml1": true, 
     "isPrasentinXml2": true, 
     "attribute": [{ 
      "name": "osname", 
      "firstValue": "Linux\u000a", 
      "secondValue": "Linux\u000a"}] 
     }, 
     { 
     "id": "1", 
     "elementName": "hostname", 
     "isEqual": false, 
     "isPrasentinXml1": true, 
     "isPrasentinXml2": true, 
     "attribute": [{ 
      "name": "hostname", 
      "firstValue": "estilo\u000a", 
      "secondValue": "buckeye.informatica.com\u000a"}] 
     } 
    ] 
}; 

alert(jsonobj.response[0].elementName); 
alert(jsonobj.response[0].attribute[0].firstValue + ", " + jsonobj.response[0].attribute[0].secondValue); 

請問我是否可以安裝並學習如何使用Firebug或Chrome的開發控制檯。這些工具可以讓你的生活變得更加簡單。