var USER_DETAILS= {
"details": [
{
"name": "john",
"passwd": "xyz",
"email": "j@g.com",
"contact": "87685778",
"lastLogin": "Sun Aug 24 2014 23:30:54 GMT+0530 (India Standard Time)"
},
{
"name": "peter",
"passwd": "xyz",
"email": "p@g.com",
"contact": "09820984",
"lastLogin": "Sun Aug 24 2014 23:41:04 GMT+0530 (India Standard Time)"
},
{
"name": "s",
"passwd": "123",
"email": "s@g.com",
"contact": "3435",
"lastLogin": "Mon Aug 25 2014 00:05:45 GMT+0530 (India Standard Time)"
},
{
"name": "y",
"passwd": "k",
"email": "j@jhj.com",
"contact": "87685778",
"lastLogin": "Mon Aug 25 2014 00:12:59 GMT+0530 (India Standard Time)"
},
{
"name": "johny",
"passwd": "234",
"email": "lkj@g.com",
"contact": "34543",
"lastLogin": "Mon Aug 25 2014 00:20:44 GMT+0530 (India Standard Time)"
}
]
}
我现在有这个jason数据我需要访问“John”这个名字。我试过像访问它一样
USER_DETAILS.details[i].name
但我收到错误USER_DETAILS.details is undefined
。
以下是我访问JSON的其余代码
function check_details()
{
var users=JSON.parse(localStorage.getItem('USER_DETAILS'));
for (var key in users)
{
alert(users.details[0].name);
}
}
答案 0 :(得分:2)
尝试这样的事情:
USER_DETAILS.details[0].name
USER_DETAILS
它是一个属性为details
的对象,它是一个数组,而'John'
位于数组的第一个实例中。
这一切在我的结尾都很合理:
var USER_DETAILS= /* your sample code */;
console.log( USER_DETAILS.details[0].name);
答案 1 :(得分:0)
试试这个
function check_details()
{
var users=JSON.parse(localStorage.getItem('USER_DETAILS'));
for (var key in users.details)
{
alert(users.details[key].name);
}
}
你试图遍历只有一个对象users
的{{1}},所以你需要遍历details
对象以获取所有用户
jsfiddle demo (without using localStorage)
供参考,有关for...in loops
的文档答案 2 :(得分:0)
错误 USER_DETAILS.details未定义,因为您的JSON字符串中存在语法错误,缺少'和' ...
你的:= {"详情":[{" name":" john",...
正确:=' {"详情":['' {"姓名":"约翰" ,...
这是一个有效的例子
var USER_DETAILS = '{"details":[' +
'{"name":"John","passwd":"1234", "email":"john@gmail.com" },' +
'{"name":"Anna","passwd":"5678", "email":"anna@gmail.com" },' +
'{"name":"Peter","passwd":"9945", "email":"peter@gmail.com" }]}';
obj = JSON.parse(USER_DETAILS);
document.getElementById("paragraphid").innerHTML =
obj.details[0].name + " " + obj.details[0].email;
最佳实践: