2014-11-14 33 views

回答

2

數組元素只是一個名爲 「」 的屬性樹鍵值:

for (auto& array_element : pt) { 
    for (auto& property : array_element.second) { 
     std::cout << property.first << " = " << property.second.get_value<std::string>() << "\n"; 
    } 
} 

打印

ID = cc7c3e83-9b94-4fb2-aaa3-9da458c976f7 
Type = VM 

Live On Coliru

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

using namespace boost::property_tree; 

int main() 
{ 
    std::istringstream iss(R"([ 
    { 
     "ID": "cc7c3e83-9b94-4fb2-aaa3-9da458c976f7", 
     "Type": "VM" 
    } 
    ] 
    )"); 

    ptree pt; 
    json_parser::read_json(iss, pt); 

    for (auto& array_element : pt) { 
     for (auto& property : array_element.second) { 
      std::cout << property.first << " = " << property.second.get_value<std::string>() << "\n"; 
     } 
    } 
} 
+0

當我看到我不能使用類似的文件'pt.get (「鑰匙」);',因爲根數組沒有鑰匙,我有過陣列使用迭代,我說的對? – likern 2014-11-15 13:26:48

+0

這是可能的。這只是我嘗試的第一件事。這種限制似乎很可能存在:你將如何處理重複密鑰 - 更不用說重複的密鑰:) – sehe 2014-11-15 14:04:17

+0

@sehe是否可以使用boost ptree在JSON中找出孩子? – 2017-03-06 11:03:44

相關問題