0

我的json是:

[
   {
      "_id":{
         "time":1381823399000,
         "new":false,
         "timeSecond":1381823399,
         "machine":263168773,
         "inc":-649466399
      },
      "asset":"RO2550AS1",
      "Salt Rejection":"90%",
      "Salt Passage":"10%",
      "Recovery":"59%",
      "Concentration Factor":"2.43",
      "status":"critical",
      "Flow Alarm":"High Flow"
   },
   [
      {
         "Estimated Cost":"USD 15",
         "AssetName":"RO2500AS1",
         "Description":"Pump Maintenance",
         "Index":"1",
         "Type":"Service",
         "DeadLine":"13 November 2013"
      },
      {
         "Estimated Cost":"USD 35",
         "AssetName":"RO2500AS1",
         "Description":"Heat Sensor",
         "Index":"2",
         "Type":"Replacement",
         "DeadLine":"26 November 2013"
      },
      {
         "Estimated Cost":"USD 35",
         "AssetName":"RO2550AS1",
         "Description":"Heat Sensor",
         "Index":"3",
         "Type":"Replacement",
         "DeadLine":"26 November 2013"
      },
      {
         "Estimated Cost":"USD 15",
         "AssetName":"RO2550AS1",
         "Description":"Pump Maintenance",
         "Index":"4",
         "Type":"Service",
         "DeadLine":"13 November 2013"
      },
      {
         "Estimated Cost":"USD 15",
         "AssetName":"RO3000AS1",
         "Description":"Pump Maintenance",
         "Index":"5",
         "Type":"Service",
         "DeadLine":"13 November 2013"
      },
      {
         "Estimated Cost":"USD 35",
         "AssetName":"RO3000AS1",
         "Description":"Heat Sensor",
         "Index":"6",
         "Type":"Replacement",
         "DeadLine":"26 November 2013"
      }
   ]
]

我需要在 javascript 中访问它。

以下代码不起作用:

var jsonobjstr = JSON.parse(jsonOutput);
alert ("asset: "+jsonobjstr.asset);
4

2 回答 2

4

因为整个JSON都包含在一个数组中。

alert("asset: "+jsonobjstr[0].asset);

http://jsfiddle.net/ExplosionPIlls/yHj5X/2/

于 2013-10-15T18:29:58.353 回答
2

在 JavaScript 中

var somename = [];表示一个新数组和; var somename = {};表示一个新对象。

因此,如果某个 json 以 a 开头,[]则表示它是一个对象数组,如果它以 {} 开头,则表示它是一个对象。

您的 json 以 开头[],因此它是一个对象数组,因此您需要通过以下方式访问每个对象:

json[n].asset对于数组的每个位置(其中 n 是整数)。

但:

你的 JSON 很奇怪。看起来您将始终拥有一个包含一个元素的数组(如果为 true,则 json 应以{}.

喜欢:

{
    "id":
    {
        "code":1381823399000
    },
    "asset":"RO2550AS1",
    "history":
    [
        {
            "value":"USD 15"
        },
        {
            "value":"USD 15"
        },
        {
            "value":"USD 15"
        }
    ]
 }

在这里你可以做:

thing.id.code
thing.asset
thing.history[0].value
thing.history[1].value
于 2013-10-15T18:33:35.813 回答