{
"data": {
"info": [
{
"username": "john",
"uid": "893y4t89hg98y7894th",
"avatar": null,
"level": null
},
{
"username": "joel",
"uid": "ui9otjry4t89hg994t",
"avatar": null,
"level": null
}
]
}
}
这是json数据。这是jsfiddle。
JS:
$(function(){
var str = '{"data":{"info":[{"username":"john","uid":"893y4t89hg98y7894th","avatar":null,"level":null},{"username":"joel","uid":"ui9otjry4t89hg994t","avatar":null,"level":null}]}}';
str = JSON.parse(str.data.info);
$.each(str, function(i, item){
$(".result1").append(item.username);
$(".result2").append(item.uid);
});
});
有人能告诉我,我做错了什么吗?
答案 0 :(得分:3)
有点不对劲。 您无法将字符串作为对象访问。
str = JSON.parse(str.data.info); //str is string, no object
$.each(str, function(i, item){
//... it wrong
str = JSON.parse(str);//parse string, get object
$.each(str.data.info, function(i, item){
//... it right
请参阅DEMO
答案 1 :(得分:0)
试试这个:
$(function(){
var str = '{"data":{"info":[{"username":"john","uid":"893y4t89hg98y7894th","avatar":null,"level":null},{"username":"joel","uid":"ui9otjry4t89hg994t","avatar":null,"level":null}]}}';
str = JSON.parse(str);
$.each(str.data.info, function(i, item){
$(".result1").append(item.username);
$(".result2").append(item.uid);
});
});
答案 2 :(得分:0)
这样可以更好地工作 - 您需要先解析字符串,然后才能访问JSON中的对象
$(function(){
var str = '{"data":{"info":[{"username":"john","uid":"893y4t89hg98y7894th","avatar":null,"level":null},{"username":"joel","uid":"ui9otjry4t89hg994t","avatar":null,"level":null}]}}';
str = JSON.parse(str);
var info = str.data.info;
$.each(info, function(i, item){
$(".result1").append(item.username);
$(".result2").append(item.uid);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="result1"></div>
<div class="result2"></div>
答案 3 :(得分:0)
你的解析是错误的。你得到str
json对象之前得到的值。
试试这个:
$(function(){
var str = '{"data":{"info":[{"username":"john","uid":"893y4t89hg98y7894th","avatar":null,"level":null},{"username":"joel","uid":"ui9otjry4t89hg994t","avatar":null,"level":null}]}}';
str = JSON.parse(str);
var info=str['data']['info'];
console.log(info);
for(var key in info){
$(".result1").append(info[key]['username']);
$(".result2").append(info[key]['uid']);
}
});
同样更新了你的小提琴。