2017-08-03 83 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對象添加到其中。