如何使用JavaScript访问JSON文档的属性?

时间:2015-11-21 14:57:07

标签: javascript arrays json

使用JavaScript,如何访问以下area文档中的JSON变量?

{

  "foo : age=39, height=170": {
  "age": 39,
  "height": 172,
  "center": {
     "area": 102,
     "local": 304
  },
  "color": "#0000ff",
  "radius": 9.5,
  "color_srv": "#aa0054"
 }
}

2 个答案:

答案 0 :(得分:1)

您需要整个属性字符串才能访问,即使它看起来有点奇怪。

var data = {
    "foo : age=39, height=170": {
        "age": 39,
        "height": 172,
        "center": {
            "area": 102,
            "local": 304
        },
        "color": "#0000ff",
        "radius": 9.5,
        "color_srv": "#aa0054"
    }
};
document.write(data['foo : age=39, height=170'].center.area);

答案 1 :(得分:0)

首先,您需要修复JSON,格式无效,因为它......

如果你要把它改成这样......

{
    "foo": {
        "age": 39,
        "height": 172,
        "center": {
            "area": 102,
            "local": 304
        },
        "color": "#0000ff",
        "radius": 9.5,
        "color_srv": "#aa0054"
    }
}

您可以使用下面的JavaScript ...

访问该变量
console.log(testing["foo"]["center"]["area"])