我正在使用 jsoncpp 将数据写入 json 格式,如下所示:
Json::Value event;
Json::Value lep(Json::arrayValue);
event["Lepton"] = lep;
lep.append(Json::Value(1));
lep.append(Json::Value(2));
lep.append(Json::Value(3));
lep.append(Json::Value(4));
event["Lepton"] = lep;
Json::StyledWriter styledWriter;
cout << styledWriter.write(event);
我得到了以下输出:
{
"Lepton" : [
1,
2,
3,
4
]
}
我想将多个这样的 block 写入我的数据文件。我最终想要的是:
[
{
"Lepton" : [
1,
2,
3,
4
]
},
{
"Lepton" : [
1,
2,
3,
4
]
}
]
目前,我正在编写 [
,然后是 json 条目,然后是 ,
,最后是 ]
。此外,我还必须删除最终数据文件中的最后一个 ,
。
有没有办法通过 jsoncpp 或其他方式自动完成所有这些工作?
谢谢
最佳答案
使用评论部分@Some prorammer dude 的建议,我做了以下事情:
Json::Value AllEvents(Json::arrayValue);
for(int entry = 1; entry < 3; ++entry)
{
Json::Value event;
Json::Value lep(Json::arrayValue);
lep.append(Json::Value(1 + entry));
lep.append(Json::Value(2 + entry));
lep.append(Json::Value(3 + entry));
lep.append(Json::Value(4 + entry));
event["Lepton"] = lep;
AllEvents.append(event);
Json::StyledWriter styledWriter;
cout << styledWriter.write(AllEvents);
}
我得到了如下所示的所需输出:
[
{
"Lepton" : [
1,
2,
3,
4
]
},
{
"Lepton" : [
2,
3,
4,
5
]
}
]
基本上,我创建了一个 Json 数组并将生成的 Json 对象附加到其中。
关于c++ - 使用 jsoncpp 将 json 数据增量写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45476392/