2017-04-17 31 views
3

這是我的JSON文件。使用Boost庫從C++檢索JSON內容

{ 
    "found":3, 
    "totalNumPages":1, 
    "pageNum":1, 
    "results": 
    [ 
     { 
      "POSTAL":"000000" 
     }, 
     { 
      "POSTAL":"111111" 
     }, 
     { 
      "POSTAL":"222222" 
     } 
    ] 
} 

這是C++代碼。

#include <boost/property_tree/ptree.hpp> 
#include <boost/property_tree/json_parser.hpp> 
#include <iostream> 

int main() 
{ 
    // Short alias for this namespace 
    namespace pt = boost::property_tree; 

    // Create a root 
    pt::ptree root; 

    // Load the json file in this ptree 
    pt::read_json("filename.json", root); 

    std::vector< std::pair<std::string, std::string> > results; 
    // Iterator over all results 
    for (pt::ptree::value_type &result : root.get_child("results")) 
    { 
     // Get the label of the node 
     std::string label = result.first; 
     // Get the content of the node 
     std::string content = result.second.data(); 
     results.push_back(std::make_pair(label, content)); 
     cout << result.second.data(); 
    } 
} 

我需要讓每一組子值的駐留在父("results"),但它打印出空白。我曾嘗試使用

root.get_child("results.POSTAL") 

但由於方括號,它會拋出錯誤。有什麼建議?

+0

這應該有助於http://stackoverflow.com/questions/17124652/how -can-i-parse-json-arrays -with-c-boost –

+2

請進入複製確切的錯誤信息到問題中。 –

回答

0

Boost中的數組屬性樹被表示爲具有多個未命名屬性的對象。

因此,在他們剛剛循環:

Live On Coliru

#include <boost/property_tree/ptree.hpp> 
#include <boost/property_tree/json_parser.hpp> 
#include <iostream> 

int main() 
{ 
    namespace pt = boost::property_tree; 
    pt::ptree root; 
    pt::read_json("filename.json", root); 

    std::vector< std::pair<std::string, std::string> > results; 
    // Iterator over all results 
    for (pt::ptree::value_type &result : root.get_child("results.")) 
     for (pt::ptree::value_type &field : result.second) 
      results.push_back(std::make_pair(field.first, field.second.data())); 

    for (auto& p : results) 
     std::cout << p.first << ": " << p.second << "\n"; 
} 

打印

POSTAL: 000000 
POSTAL: 111111 
POSTAL: 222222