如何从嵌套JSON获取特定或多个值(或键) [英] How to get a specific or multiple values (or keys) from nested JSON
问题描述
我有一个(嵌套的)数据结构,其中包含对象和数组.如何提取信息,即访问特定或多个值(或键)?
I have a (nested) data structure containing objects and arrays. How can I extract the information, i.e. access a specific or multiple values (or keys)?
{
"data": [{
"name": "name1",
"value": "value1",
"list": [{
"sname": "sname1",
"svalue": "svalue1"
}, {
"sname": "sname2",
"svalue": "svalue2"
}]
}]
}
jQuery
var pk = $("#pk").val();
console.log(pk);
url = "/register/search?id=" + pk;
console.log(url);
$('#largeTable').DataTable({
"ajax": url,
"bDestroy": true,
"columns": [{
"data": "name"
},
{
"data": "value"
},
{
"data": "list.1.sname"
},
{
"data": "list.1.svalue"
},
{
"data": null,
"defaultContent": editview
}
]
});
在这里可以使用list.1或list.0显示第一或第二个列表值
Here it is possible to display either first or second list values by using list.1 or list.0
但是我一次想要两个值.
But I want two values at a time.
还可以访问list
中第二项的svalue
吗?
Also, how could I access the svalue
of the second item in list
?
我尝试使用data.list[1]
,但是:
TypeError:data.list未定义
TypeError: data.list is undefined
推荐答案
具体地说,您可以像object.data[0].list[1].svalue
这样访问它. data.list
是undefined
的原因是因为data
对应于数组data: [{ }]
,这就是我们使用data[0]
的原因,但是data
本身是对象中的键,因此在进入data
之前您需要访问它.如果data
所在的对象名称是object
(就像我在下面所做的那样),则可以像这样object.data[0]
Specifically you can access it like this object.data[0].list[1].svalue
. The reason data.list
is undefined
is because data
corresponds to an array data: [{ }]
this is why we use data[0]
, but data
itself is a key in an object so before you can get to data
you need to access it. If the objects name where data
resides were object
(like I did below) then it'd be accessed like this object.data[0]
const object = {
"data": [{
"name": "name1",
"value": "value1",
"list": [{
"sname": "sname1",
"svalue": "svalue1"
}, {
"sname": "sname2",
"svalue": "svalue2"
}]
}]
}
console.log(object.data[0].list[1].svalue)
这篇关于如何从嵌套JSON获取特定或多个值(或键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!