JavaScript如何解析JSON数组获取指定id字段值?
问题原因
- 你代码中声明的
myJson本身已经是JavaScript对象,不是JSON字符串,不需要调用JSON.parse()解析,该方法仅支持传入JSON格式字符串作为参数,直接传入对象会触发运行错误。 - 你想要的
id字段在searchResults数组下,需要先定位到该数组再取对应值。
解决方案
场景1:确定目标id在数组的第二个位置(索引为1)
直接通过层级取值即可:
<script> var myJson = { "searchResults": [ { "self": "https://api.icims.com/customers/xxxx/applicantworkflows/689997", "id": 689997 }, { "self": "https://api.icims.com/customers/xxxx/applicantworkflows/691005", "id": 691005 } ] } // 直接通过层级取值 const targetId = myJson.searchResults[1].id; console.log(targetId); // 输出 691005 </script>
场景2:数组顺序不固定,需要匹配id为691005的项
可以用Array.prototype.find()方法过滤匹配:
<script> var myJson = { "searchResults": [ { "self": "https://api.icims.com/customers/xxxx/applicantworkflows/689997", "id": 689997 }, { "self": "https://api.icims.com/customers/xxxx/applicantworkflows/691005", "id": 691005 } ] } // 过滤匹配id为691005的项 const targetItem = myJson.searchResults.find(item => item.id === 691005); const targetId = targetItem ? targetItem.id : null; console.log(targetId); // 输出 691005 </script>
内容的提问来源于stack exchange,提问作者Tim
相关产品推荐
相关产品推荐

