How to read a JSON file containing multiple root elements?

两盒软妹~` 提交于 2019-12-17 10:01:17

问题


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
}

回答1:


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



回答2:


No one has mentioned arrays:

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

Is valid JSON and might do what the OP wants.




回答3:


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.



来源:https://stackoverflow.com/questions/11639886/how-to-read-a-json-file-containing-multiple-root-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!