How to read a JSON file containing multiple root elements?

Viewed 28741

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 (using JsonCpp). But what if the structure of the file was less convenient like this:

{
   "one":1
}

{
   "two":2
}
4 Answers

No one has mentioned arrays:

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

Is valid JSON and might do what the OP wants.

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;
   }
Related