从JSON数组中检索数组值

时间:2015-12-08 04:43:13

标签: jquery arrays json ajax

我正在尝试检索JSON数组中存在的值。但是,我的代码无法执行它.Below发布的是该文件的样子。

{
  "meta" : {
    "view" : {
      "description" : "This data set shows the location of Baltimore City's Services.",
      "columns" : [{
          "cachedContents" : {
            "top" : [{
                "item" : "American Rescue Workers"
              }
            ]
          }
        }
      ]
    }
  }

我的抱歉,如果我的JSON文件有一些语法问题。我正在尝试访问cachedContents中的item元素。发布的是代码。

$(document).ready(function () {

    $.get("https://data.baltimorecity.gov/api/views/hyq3-8sxr/rows.json", function (data) {
        $.each(data.meta.view, function (i, obj) {
            if (i == "name")
                $("#result").append("<p align='center'>" + obj + "</p>");
            if (i == "description")
                $("#result").append("<p>" + obj + "</p>");
            if (i == "columns")
                $.each(obj.i.cachedContents, function (i1, obj) {
                    $("#result").append("<p>" + "hi" + "</p>");
                });
        });
    });

});

任何建议都会非常有用。

2 个答案:

答案 0 :(得分:3)

您的JSON包含很多字段,并且使用if进行迭代可能会遇到一些性能问题。

您可以直接访问每个成员:

&#13;
&#13;
$(document).ready(function () {

  $.get("https://data.baltimorecity.gov/api/views/hyq3-8sxr/rows.json", function (data) {			
    $("#result").append("<p align='center'>" + data.meta.view.name + "</p>");
    $("#result").append("<p>" + data.meta.view.description + "</p>");

    data.meta.view.columns.forEach(function(c) {
      // here, 'c' is a column
      $("#result").append("<p>Column " + c.name + "</p>");
    });
  });

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="result"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

应该是

$.each(obj[0].cachedContents, function(i1, obj) {
      $("#result").append("<p>" + "hi" + "</p>");
    });

对象[0]不是&#34;我&#34;。

相关问题