我只是想从json数组中读取json对象。但是在尝试读取整个数组时,我得到了[Object]
来代替嵌套的Json对象。
我的JSON看起来像这样:
var json = {
"root_id": [
{
"child-id1": {
"name": "name1",
"created_by": null,
"created_at": "2018-05-30T19:34:38.657Z",
"configs": {
"generic": {
"size": 1000,
"timeout": 60,
"field1_key": "field1_value"
},
"specific": {
"key1": "xxx-xxx",
"field1_key": "field1_value"
}
}
}
},
{
"child-id2": {
"name": "name2",
"created_by": null,
"created_at": "2018-05-30T19:34:38.657Z",
"configs": {
"generic": {
"size": 10,
"timeout": 60,
"field1_key": "field1_value"
},
"specific": {
"key1": "xxx-xxx",
"field1_key": "field1_value"
}
}
}
}
]
}
我希望我的函数返回“ root_id”对象的Json数组。因此,我只是尝试了以下简单代码来读取数组:
var val = json['root_id'];
console.log(val);
但是它返回此:
[ { 'child-id1':
{ name: 'name1',
created_by: null,
created_at: '2018-05-30T19:34:38.657Z',
configs: [Object] } },
{ 'child-id2':
{ name: 'name2',
created_by: null,
created_at: '2018-05-30T19:34:38.657Z',
configs: [Object] } } ]
如何确保嵌套对象返回原样,而不只是 [object] ?
答案 0 :(得分:3)
如果在服务器中使用此console.log
,则应使用util.inspect()
,https://nodejs.org/api/util.html。
检查以下问题:How can I get the full object in Node.js's console.log(), rather than '[Object]'?
如果在浏览器中使用,它应该显示所有内容。
答案 1 :(得分:0)
尝试
var json = {
"root_id": [
{
"child-id1": {
"name": "name1",
"created_by": null,
"created_at": "2018-05-30T19:34:38.657Z",
"configs": {
"generic": {
"size": 1000,
"timeout": 60,
"field1_key": "field1_value"
},
"specific": {
"key1": "xxx-xxx",
"field1_key": "field1_value"
}
}
}
},
{
"child-id2": {
"name": "name2",
"created_by": null,
"created_at": "2018-05-30T19:34:38.657Z",
"configs": {
"generic": {
"size": 10,
"timeout": 60,
"field1_key": "field1_value"
},
"specific": {
"key1": "xxx-xxx",
"field1_key": "field1_value"
}
}
}
}
]
}
var count = Object.keys(json['root_id']).length;
for (var i = 0; i < count; i++) {
console.log(json['root_id'][i]);
}