【问题标题】:writing json data incremently into a file using jsoncpp使用 jsoncpp 将 json 数据增量写入文件
【发布时间】:2017-08-03 06:24:08
【问题描述】:

我正在使用 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
   ]
}

我想将多个这样的块写入我的数据文件。我最终想要的是:

[
    {
       "Lepton" : [
          1,
          2,
          3,
          4
       ]
    },
    {
       "Lepton" : [
          1,
          2,
          3,
          4
       ]
    }
]

目前,我正在编写 [,然后是 json 条目,然后是 ,,最后是 ]。我还必须删除最终数据文件中的最后一个,

有没有办法通过 jsoncpp 或其他方式自动完成所有这些操作?

谢谢

【问题讨论】:

  • 你显示的输出是你显示的代码的实际输出吗?还是预期的输出?请向我们展示两者
  • 刚刚添加了所需的输出。
  • 那你需要一个outer数组,在其中添加多个event对象,并写入外层数组对象。
  • @Someprogrammerdude 感谢您提供线索。让我试试看。
  • @Someprogrammerdude 我在下面的答案中包含了基于您的建议的代码。我希望你一切都好。

标签: c++ json jsoncpp


【解决方案1】:

使用 cmets 部分中@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 对象附加到其中。

【讨论】:

    猜你喜欢
    • 2013-05-17
    • 1970-01-01
    • 2019-07-03
    • 2015-02-13
    • 1970-01-01
    • 2016-07-09
    • 2017-04-15
    • 2018-05-26
    • 1970-01-01
    相关资源
    最近更新 更多