Search code examples
c++jsoncpp

How to read a JSON file containing multiple root elements?


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
}

Solution

  • 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 separate 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
    }
    

    If your really need separate objects, you can do it like this:

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