Search code examples
jqueryjsongetjson

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*/
         "Article": { "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?


Solution

  • 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" }, 
              ...] }