访问JSON字符串值

Access a JSON string value

本文关键字:字符串 JSON 访问      更新时间:2023-09-26

我有这个例子,我试图访问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是我的数据是在实际代码

您的错误是您的JSON周围有引号,它被视为字符串。另外,您忘记在第二个alert中将compareData变量名称替换为jsonobj。试试下面的小提琴,它似乎是你想要的。

jsFiddle: http://jsfiddle.net/Dna9H/6/

编辑:

如果您的JSON确实由字符串表示,请查看Michael Sagalovich解决方案。

试试这个

http://jsfiddle.net/Dna9H/8/

在我看来,您的对象是字符串。首先需要将其解析为对象。compareData = JSON.parse(compareData)可能会有所帮助(我认为大多数浏览器都支持JSON.parse)。jQuery也有解析器:$.parseJSON(compareData) .

您的语法。如此:

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的开发控制台。