Json中的嵌套对象
问题描述:
我是Json对象和Json数组中的新手。我想访问Json对象中的嵌套对象,但是我犯了一个小错误,我浪费了2小时的时间搜索,也在阅读大量的*的问题,但是我找不到我犯的错误。请帮我出Json中的嵌套对象
响应
{ __v: 0,
friends_in:
[ { friends_in_email: '12',
friends_in_gcm_regId: '12'
} ]
}
我的代码
console.log(JSON.stringify(doc));
输出:
{
"__v": " 0",
"friends_in": [
{
"friends_in_email": "12",
"friends_in_gcm_regId": "12"
}
]
}
下面是错误发生说不确定
mycode的
console.log(JSON.stringify(doc[0].__v));
console.log(JSON.stringify(doc[0].friends_in));
输出
0 //Correct
undefined //Why ?
答
有你的字符串化JSON了一些错误(粘贴也许一些错误?)。但使用下面的JSON,一切都按预期工作。
var rawString = '{ "__v":" 0", "friends_in": [{ "friends_in_email": "12", "friends_in_gcm_regId": "12"}] }';
var x = JSON.parse(rawString);
console.log(JSON.stringify(x.__v));
console.log(JSON.stringify(x.friends_in));
上述结果在下面的输出:
0
[{"friends_in_email":"12","friends_in_gcm_regId":"12"}]
你似乎是混合了JSON对象(事物在大括号{...})和JSON阵列(事情在方括号[ ...])。只有JSON阵列应该被索引就像你有:
var y = [22, 24, 28];
y[0] // do something with it ...
对象应该有自己的成员按名称访问:
var z = { test: 22, another_number: 24 };
z.test // do something with it ...
非常感谢,我看到你已经使用JSON.parse()来这是在使用解析一个JSON,这帮助我访问“friends_in_email” –