如何从JSON数组中的嵌入对象中检索值?

时间:2018-06-05 08:29:29

标签: jquery json ajax

我想从以下JSON对象中检索名称:

enter image description here

在我的AJAX响应函数中,我有以下内容:

success: function (response) {
    .each(response, function (idx, obj) {
         console.log(obj[1]);
         var name = obj.author["name"];
         generatedHtml.push(`${name} <br><br>`);
    });
},

我一直收到错误obj.author is undefined。我该怎么办?

编辑:完整的JSON可在此处找到:https://gist.github.com/SeloSlav/acb223dd25c589c660c7326dbf3e7bdc

1 个答案:

答案 0 :(得分:1)

虽然您可能需要更改JSON文件,但在当前状态下,您需要遍历所有键/值对,并找到key author 的那个,然后在自己的value再次是键/值对列表)上执行相同操作,并搜索key 名称

&#13;
&#13;
$.ajax({
  url: 'https://gist.githubusercontent.com/SeloSlav/acb223dd25c589c660c7326dbf3e7bdc/raw/832a489c6eeb87913712862e0798a13c1c62b161/gistfile1.txt',
  dataType: 'json',
  success: function(response) {
    $.each(response, function(idx, obj) {
      var name,
          author = obj.find(function(node) {return node.key === 'author'});
      if (author) {
        name = author.value.find(function(node) {return node.key === 'name'});

        if (name) {
          console.log(name.value);
          //generatedHtml.push(`${name.value} <br><br>`);
        }
      }
    });
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

相关问题