首页 > 解决方案 > 如何从 JSON 数组中的嵌入对象中检索值?

问题描述

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

在此处输入图像描述

在我的 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

标签: jqueryjsonajax

解决方案


尽管您可能需要更改 JSON 文件,但在当前状态下,您需要遍历所有键/值对并找到带有authorkey的那个,然后自行执行相同操作(这又是一个键/值列表对) 并搜索名称为的对valuekey

$.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>`);
        }
      }
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


推荐阅读