如何验证具有多个根元素的JSON

时间:2015-09-07 17:19:25

标签: java json

我正在使用代码,该代码以下列格式显示文件。

{"swap":1,"si":11},{"system":1,host:"new"},{"Cpu":1}

如果我验证此文件数据,则会收到错误消息:

  

第4行的解析错误:

     

...":1," si":11},{" system":1,   --------------------- ^期待' EOF'

如何解决此问题?

4 个答案:

答案 0 :(得分:1)

在构建时将个对象包装到JsonArray。然后在中迭代数组。

答案 1 :(得分:1)

中,每个密钥都是双引号"key"。您的在主机密钥上缺少双引号。确保您正在撰写格式正确的

{ "system": 1, "host": "new" }
               ^    ^

答案 2 :(得分:0)

我不是JSON的专家,但我认为您想要更改类似数值的JSON

[{"swap":1,"si":11},{"system":1,host:"new"},{"Cpu":1}]

insted of

{"swap":1,"si":11},{"system":1,host:"new"},{"Cpu":1}

答案 3 :(得分:0)

即使您有复杂的对象,也可以使用此自定义功能。

static getParsedJson(jsonString) {
    const parsedJsonArr = [];
    let tempStr = '';
    let isObjStartFound = false;
    for (let i = 0; i < jsonString.length; i += 1) {
        if (isObjStartFound) {
            tempStr += jsonString[i];
            if (jsonString[i] === '}') {
                try {
                    const obj = JSON.parse(tempStr);
                    parsedJsonArr.push(obj);
                    tempStr = '';
                    isObjStartFound = false;
                } catch (err) {
                    // console.log("not a valid JSON object");
                }
            }
        }
        if (!isObjStartFound && jsonString[i] === '{') {
            tempStr += jsonString[i];
            isObjStartFound = true;
        }
    }
    return parsedJsonArr;
}
相关问题