jquery - 如何从 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
解决方案
尽管您可能需要更改 JSON 文件,但在当前状态下,您需要遍历所有键/值对并找到带有authorkey
的那个,然后自行执行相同操作(这又是一个键/值列表对) 并搜索名称为的对value
key
$.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>
推荐阅读
- spring-boot - 我将如何隔离客户端访问,keycloak 配置
- azure - Azure Functions App:发布 Docker 容器的功能是什么?
- python - 将ASCII字符串编码的数组转换为字符串?
- git - git:修剪/删除旧分支:“错误:未能推送一些参考”
- java - 从数组中反转linkedList
- mysql - 从 MySql 中查找重复项
- powershell-4.0 - 如何从 powershell 提示符中删除“username@host”?
- r - 如何将 rpivotTable 结果转换为数据框
- ios - 如何在swift UITest中点击谷歌地图标记
- angular - 从 Springboot+Angular Jar 创建的 docker 镜像的单一构建多部署