[英]How do I access data in a nested json with lists?
This has been a real pain for me and I can't solve it.这对我来说是一个真正的痛苦,我无法解决它。 I have a Json that looks like this:我有一个看起来像这样的 Json:
"name": "The data",
"list": [
{
"item": "a613424",
"locations": [
{
"name": "start",
"a": 5.743,
"b": 0.093
}
]
},
{
"item": "e88934",
"locations": [
{
"name": "start",
"a": 6.64,
"b": 0.43
}
]
},
{
"item": "d92213",
"locations": [
{
"name": "start",
"a": 12.33,
"b": 0.91
},
{
"name": "stop",
"a": 889,
"b": 1.134
}
]
}]}
Every item has an item code, and in locations has a name and values for a and b.每个项目都有一个项目代码,并且在位置有一个名称和 a 和 b 的值。 Some items have 2 names.有些项目有 2 个名称。 I need to read through this and extract the item code, name(s) and a and b values.我需要通读并提取项目代码、名称以及 a 和 b 值。 I don't know how many items will be in the json or which items will have multiple names.我不知道 json 中有多少项目,或者哪些项目有多个名称。
I either get an object returned or 'unknown'我要么收到 object 要么返回“未知”
x = test_data.list[0]; document.write(x);
outputs [object object]输出[对象对象]
document.write(test_data[0]);
outputs 'undefined'输出“未定义”
I could do this in 5 minutes in Python, but sadly this has to be in javascript.我可以在 Python 中在 5 分钟内完成此操作,但遗憾的是这必须在 javascript 中。
Thanks谢谢
Access the lists through forEach
and item
and locations
properties.通过forEach
和item
和locations
属性访问列表。 It's easy since you have a constant structure for your JSON这很容易,因为您的 JSON 具有恒定的结构
let data = { "name": "The data", "list": [{ "item": "a613424", "locations": [{ "name": "start", "a": 5.743, "b": 0.093 }] }, { "item": "e88934", "locations": [{ "name": "start", "a": 6.64, "b": 0.43 }] }, { "item": "d92213", "locations": [{ "name": "start", "a": 12.33, "b": 0.91 }, { "name": "stop", "a": 889, "b": 1.134 } ] } ] }; let listItems = data.list; listItems.forEach(item => { console.log("item code: " + item.item); // item code item.locations.forEach(location => { console.log("location a is: " + location.a); // a console.log("location b is: " + location.b); // b }); console.log("\n"); //for breakline });
let objectData = { name: "The data", list: [ { item: "a613424", locations: [ { name: "start", a: 5.743, b: 0.093 } ] }, { item: "e88934", locations: [ { name: "start", a: 6.64, b: 0.43 } ] }, { item: "d92213", locations: [ { name: "start", a: 12.33, b: 0.91 }, { name: "stop", a: 889, b: 1.134 } ] } ] }; let obDList = objectData.list.map((x) => x.locations.map((y) => { return `a = ${ya}, b = ${yb} `; }) ); console.log(obDList); console.log(obDList[2][1]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.