jquery parse json
I can't parse the JSON that I have no control of. What am I doing wrong here?
data.json
{
"img": "img1.jpg",
"img": "img2.jpg",
"size": [52, 97]
}
{
"img": "img3.jpg",
"img": "img4.jpg",
"size": [52, 97]
}
jquery
$.getJSON("data.json",
function(data){
$.each(data, function(i,item){
开发者_运维知识库 alert(item.img[i]);
});
});
The JSON is badly formed. It should be something like this:
{images: [{
"img": "img1.jpg",
"img": "img2.jpg",
"size": [52, 97]
},
{
"img": "img3.jpg",
"img": "img4.jpg",
"size": [52, 97]
}]
}
That's why you're having trouble parsing it.
If you don't have control over it, but you know that it's going to be in a similar form, you can use jQuery.ajax
and then convert it over to valid JSON through some string manipulation or something. Probably not ideal, but it's the only thing you can do given that you have no control over the JSON being returned.
Also note that you have two keys with the same name. That's another problem.
To fix that, you probably want something like the following:
{images: [{
"img1": "img1.jpg",
"img2": "img2.jpg",
"size": [52, 97]
},
{
"img3": "img3.jpg",
"img4": "img4.jpg",
"size": [52, 97]
}]
}
or
{images: [{
"img": ["img1.jpg", "img2.jpg"],
"size": [52, 97]
},
{
"img": ["img3.jpg", "img4.jpg"],
"size": [52, 97]
}]
}
I think an even better way would be something like this:
{images: [{
img: "img1.jpg",
size: [52, 97]
},
{
img: "img2.jpg",
size: [52, 97]
},
{
img: "img3.jpg",
size: [52, 97]
},
{
img: "img4.jpg",
size: [52, 97]
}]
}
Like I mentioned before, given that you have no control over the JSON there is little you can do. I would recommend talking to the admin/developer of that site if you can, though. They do need to be informed that they are not returning valid JSON.
精彩评论