I get one instead of many entries after loading JSON with JQuery
I've built some JSON
{
"News": {
"Article": {"title": "test"},
"Article": { "title": "test" },
/*Snipped*/
"Ar开发者_如何学JAVAticle": { "title": "test" },
"Article": { "title": "test" }
},
"count": "20"
}
which validates in a JSON formatter. But when I try to ingest this data through jQuery I don't get what's expected:
$.getJSON('php/json.php', function(data) {
console.log(data);
});
Results:
News: Object
Article: Object
title: "test"
__proto__: Object
__proto__: Object
count: "20"
But where are my 19 other Article objects? I'm new to JSON and jQuery's getJSON
. Is there anything I'm missing?
JavaScript objects are dictionaries, which means that the name must be unique. You're replicating Article
, so each instance overwrites the previous (or is ignored; I don't know which path the parser takes).
To fix, you need to define this name as referencing an array:
{ "News": { "Article": [
{ "title": "test" },
{ "title": "test" },
...],
"count": "20" }
But you could probably reduce this further, assuming that all news items are articles, because count
becomes superfluous:
{ "News": [
{ "title": "test" },
{ "title": "test" },
...] }
A better format would be
{
"News": {
"1": {"title": "test","type":"article"},
"2": {"title": "test","type":"article"},
/*Snipped*/
"19": {"title": "test","type":"article"},
"20": {"title": "test","type":"article"}
},
"count": "20"
}
So you can do with each.
$.each(Object.news,function(id,ObjectItem){
if(ObjectItem.type == 'article')
{
//do something with ObjectItem.title
}
})
You defined the Article
-key multiple times. This is not a syntax error (which is why the formatter does not complain) but rather a logical one. You should use an array instead.
精彩评论