2017-08-03 45 views
1

我使用jsoncpp将数据写入到JSON格式像下面写JSON数据incremently到一个文件:使用jsoncpp

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或其他方式自动完成所有这些?

感谢

+0

您显示的代码的输出是* actual *的输出结果吗?或者它是*期望*输出?请向我们展示* *。 –

+0

只是添加了所需的输出。 – Pankaj

+1

然后,您需要一个* outer *数组,在其中添加多个“事件”对象,并写入外部数组对象。 –

回答

1

运用在评论部分@Some prorammer老兄的建议,我做了以下内容:

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对象添加到其中。