首页 > 解决方案 > 使用 getJSON 休息调用读取 json 对象序列

问题描述

我已经实现了一个 REST 服务,它提供了具有这种结构的 json 数据序列。

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

我需要使用 getJSON 解析 javascript 中的这些 json 数据,并打印例如“foo”值。

我在 JSON 数据的第 1 行第 115 列收到 SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data

我使用的代码如下:

    $.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);
        })
    })

我认为 getJSON 不喜欢不同对象后没有逗号

标签: jsonrestgetjson

解决方案


你的 json 不应该打印得很漂亮。当大括号中有空格(空白、新行、制表符...)时,许多解析器会抛出错误/异常。只需整理您的 json,它应该可以工作。


推荐阅读