【发布时间】:2020-02-12 09:25:12
【问题描述】:
我有一个场景,我试图通过下面的 json 解析并获取 key "name" 和 key "id" 的所有值,我会进一步将它们存储在变量或数组中。
[
{
"metadata": {
"id": "vvvvvvvvvvvvv",
"url": "cccccccccccccc",
"created_at": "2019-09-06T08:40:41Z",
"updated_at": "2019-09-06T13:25:46Z"
},
"entity": {
"name": "app1",
"b_enabled": false,
"d_url": "xxxxxs"
}
},
{
"metadata": {
"id": "vvvvvvvvvvccc",
"url": "cccccccccccccc",
"created_at": "2019-09-06T08:40:41Z",
"updated_at": "2019-09-06T13:25:46Z"
},
"entity": {
"name": "app2",
"b_enabled": false,
"d_url": "xxxxxs"
}
},
{
"metadata": {
"id": "vvvvvvvvvvddd",
"url": "cccccccccccccc",
"created_at": "2019-09-06T08:40:41Z",
"updated_at": "2019-09-06T13:25:46Z"
},
"entity": {
"name": "app3",
"b_enabled": false,
"d_url": "xxxxxs"
}
},
{
"metadata": {
"id": "vvvvvvvvvveee",
"url": "cccccccccccccc",
"created_at": "2019-09-06T08:40:41Z",
"updated_at": "2019-09-06T13:25:46Z"
},
"entity": {
"name": "app4",
"b_enabled": false,
"d_url": "xxxxxs"
}
},
{
"metadata": {
"id": "vvvvvvvvvvfff",
"url": "cccccccccccccc",
"created_at": "2019-09-06T08:40:41Z",
"updated_at": "2019-09-06T13:25:46Z"
},
"entity": {
"name": "app5",
"b_enabled": false,
"d_url": "xxxxxs"
}
}
]
我到目前为止所尝试的(在此之后不确定如何进行,因为这本身提供了错误的结果)
const dJSON = require('dirty-json');
const jsn = dJSON.parse(get_all)
console.log(JSON.stringify(jsn));
jsonData = JSON.stringify(jsn)
console.log(jsonData.length) //this returns wrong value
for(var i = 0; i < jsonData.length; i++){
for(key in jsonData[i].entity){
if(jsonData[i].entity[key] == "name"){
return console.log(key);
}
}
}
这不会返回预期的输出。 有人可以在这里提出建议,因为我是 nodejs 和 javascript 的新手,如何提取这样的结果
预期 o/p :
{
"app1" : "vvvvvvvvvvvvv",
"app2" : "vvvvvvvvvvccc",
"app3" : "vvvvvvvvvvddd",
"app4" : "vvvvvvvvvveee",
"app5" : "vvvvvvvvvvfff"
}
【问题讨论】:
-
metadata键和entity键是否始终相同 -
@Nicolas 确实
标签: javascript arrays node.js json loops