How to read a JSON file containing multiple root elements?

前端 未结 4 1320
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 00:10

If I had a file whose contents looked like:

{\"one\": 1}
{\"two\": 2}

I could simply parse each separate line as a separate JSON object (us

相关标签:
4条回答
  • 2020-12-02 00:51

    Rob Kennedy is right. Calling it a second time would extract the next object, and so on.Most of the json lib can not help you to do all in a single root. Unless you are using more high end framework in QT.

    0 讨论(0)
  • 2020-12-02 00:56

    Neither example in your question is a valid JSON object; a JSON object may only have one root. You have to split the file into two objects, then parse them.

    You can use http://jsonlint.com to see if a given string is valid JSON or not.

    So I recommend either changing what ever is dumping multiple JSON objects into a single file to do it in seperate files, or to put each object as a value in one JSON root object.

    If you don't have control over whatever is creating these, then you're stuck parsing the file yourself to pick out the different root objects.

    Here's a valid way of encoding those data in a JSON object:

    {
        "one": 1,
        "two": 2
    }
    

    or if your really need seperate objects, like this:

    {
        "one":
        {
            "number": 1
        },
        "two":
        {
            "number": 2
        }
    }
    
    0 讨论(0)
  • 2020-12-02 01:07

    No one has mentioned arrays:

    [
      {"one": 1},
      {"two": 2}
    ]
    

    Is valid JSON and might do what the OP wants.

    0 讨论(0)
  • 2020-12-02 01:07

    You can also use this custom function to parse multiple root elements even if you have complex objects.

        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;
       }
    
    0 讨论(0)
提交回复
热议问题