Search code examples
jsonrestgetjson

Read sequence of json objects with getJSON rest call


I have implemented a REST service which provides a sequence of json data with this structure.

{
    "item":
            {
            "att1":"foo",
            "att2":"foo",
            "att3":"foo"
            }
}
{   
    "item":
            {
            "att1":"foo",
            "att2":"foo",
            "att3":"foo"
            }
}
{   
    "item":
            {
            "att1":"foo",
            "att2":"foo",
            "att3":"foo"
            }
}

I need to parse those json data in javascript with getJSON, and print for instance the "foo" values.

I get SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 115 of the JSON data

The code i used is the following:

    $.getJSON("http://localhost:8080/rest/item", function(data) {
        $.each(data.item, function(index,element) {
            console.log(element.att1);
            console.log(element.att2);
            console.log(element.att3);
        })
    })

I think getJSON does not like the absence of commas after different objects


Solution

  • Your json should not be pretty printed. Many parser throw errors/exceptions when there are whitespaces (blank, new line, tab ... ) within the braces. Just untidy your json and it should work.