无法获得json属性

时间:2017-06-11 16:38:03

标签: javascript json

如何使用JavaScript从JSON获取所有名称属性?

{
  "layerGroup": {
    "name": "tasmania",
    "mode": "SINGLE",
    "title": "Tasmania",
    "abstractTxt": "Tasmania Australia from Digital Chart of the World.",
    "publishables": {
      "published": [{
        "@type": "layer",
        "name": "tasmania_state_boundaries",
        "href": "http:\/\/localhost:8080\/geoserver\/rest\/layers\/tasmania_state_boundaries.json"
      }, {
        "@type": "layer",
        "name": "tasmania_water_bodies",
        "href": "http:\/\/localhost:8080\/geoserver\/rest\/layers\/tasmania_water_bodies.json"
      }, {
        "@type": "layer",
        "name": "tasmania_roads",
        "href": "http:\/\/localhost:8080\/geoserver\/rest\/layers\/tasmania_roads.json"
      }, {
        "@type": "layer",
        "name": "tasmania_cities",
        "href": "http:\/\/localhost:8080\/geoserver\/rest\/layers\/tasmania_cities.json"
      }]
    },
    "styles": {
      "style": ["null", "null", "null", "null"]
    },
    "bounds": {
      "minx": 143.83482400000003,
      "maxx": 148.47914100000003,
      "miny": -43.648056,
      "maxy": -39.573891,
      "crs": "EPSG:4326"
    },
    "metadata": {
      "entry": {
        "@key": "rawStyleList",
        "$": ""
      }
    }
  }
}

2 个答案:

答案 0 :(得分:1)

这是你想要的吗? 您需要循环layerGroup.publishables.published并获取名称。



var data = {"layerGroup":{"name":"tasmania","mode":"SINGLE","title":"Tasmania","abstractTxt":"Tasmania Australia from Digital Chart of the World.","publishables":{"published":[{"@type":"layer","name":"tasmania_state_boundaries","href":"http://localhost:8080/geoserver/rest/layers/tasmania_state_boundaries.json"},{"@type":"layer","name":"tasmania_water_bodies","href":"http://localhost:8080/geoserver/rest/layers/tasmania_water_bodies.json"},{"@type":"layer","name":"tasmania_roads","href":"http://localhost:8080/geoserver/rest/layers/tasmania_roads.json"},{"@type":"layer","name":"tasmania_cities","href":"http://localhost:8080/geoserver/rest/layers/tasmania_cities.json"}]},"styles":{"style":["null","null","null","null"]},"bounds":{"minx":143.83482400000003,"maxx":148.47914100000003,"miny":-43.648056,"maxy":-39.573891,"crs":"EPSG:4326"},"metadata":{"entry":{"@key":"rawStyleList","$":""}}}};

for (var i =0; i<data.layerGroup.publishables.published.length; i++){
console.log(data.layerGroup.publishables.published[i].name);
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您需要为published中的每个项目编写foreach循环。 而不是alert(data.layerGroup.name); 您需要访问已发布的对象及其“名称”属性。 现在您正在访问'layerGroup'的'name'属性