2011-07-15 109 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的开发控制台。这些工具可以让你的生活变得更加简单。