问题描述
如果我有一个内容如下的文件:
{one:1}
{两个:2}
我可以简单地将每个单独的行解析为一个单独的JSON对象href =http://jsoncpp.sourceforge.net/> JsonCpp )。但是如果文件的结构不太方便,如果这样:
{
one:1
}
{
two:2
}
您的问题中的示例都不是有效的JSON对象;一个JSON对象只能有一个根。您必须将文件拆分为两个对象,然后解析它们。
您可以使用查看给定的字符串是否为有效的JSON。
因此,我建议您更改将多个JSON对象转储为单个文件在单独的文件中执行,或者将每个对象作为值存储在一个JSON根对象中。
如果您无法控制创建这些对象,
这是一种在JSON对象中编码这些数据的有效方法:
{
one:1,
two:2
}
或者如果你真的需要单独的对象,例如:
{
one:
{
number:1
},
two:
{
number:2
}
}
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 }
解决方案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 } }
这篇关于如何读取包含多个根元素的JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!