我想编写像这个例子这样的json,并在我的程序中使用它
{
"users":[{"name":"a","age":4},{"name":"b","age":7}],
"items":[{"name":"item1","price":"$44.2"},{"name":"item2","price":"$12.5"}]
}
那么,我的 json 是正确的吗?
如果"是",我如何将其放入数组中以使用它,例如以下代码:
let users= //some thing that give me the data of users from the json
this.users.forEach(u=>{
console.log(u.name+" "+u.age)
});
如果我的 JSON 不正确,请尝试帮助我!
注意:
我的完整 JSON 已经上传到服务器上,我使用此代码来获取它
getJson(){
let url="MY JSON URL";
this.http.get(url).map(res => res.json()).subscribe(data => {
// the data received without problem
...
let users= //some thing that give me the data of users from the json
users.forEach(u=>{
console.log(u.name+" "+u.age)
});
});
}
您应该
从data
而不是this
中读取users
。 this.users
可能undefined
.检查下面的代码
getJson(){
let url="MY JSON URL";
this.http.get(url).map(res => res.json()).subscribe(data => {
// the data received without problem
...
const { users } = data;
users.forEach(user => {
console.info(`${user.name} ${user.age}`);
});
});
}