2017-09-22 106 views
0

我想獲取具有IP地址的節點的子節點。 以下是我使用的參考JSON格式和代碼。Boost JSON解析器和IP地址

{ 
"nodes":{ 
    "192.168.1.1": { 
    "type":"type1",   
    "info":"info1", 
    "error":"error1" 
    }, 
    "192.168.1.2":{ 
    "type":"type2",   
    "info":"info2", 
    "error":"error2" 
    }, 
    "test":{ 
    "type":"type2",   
    "info":"info2", 
    "error":"error2" 
    } 
} 
} 

下面是參考代碼來讀取上面的json數據。

using boost::property_tree::ptree; 
ptree pt; 
std::string ttr("test.json"); 
read_json(ttr, pt); 

BOOST_FOREACH(ptree::value_type &v, pt.get_child("nodes")) 
{ 
    std::string key_ = v.first.data(); 
    std::string val_ = v.second.data();   

    boost::optional< ptree& > child = pt.get_child_optional("nodes.192.168.1.1"); 
    if(!child) 
    { 
     std::cout << "Child Node Missing.............." << std::endl; //Always shows Node Missing. How to deal with "." as key ? 
    } 
    else 
     std::cout << "Child Node Not Missing.............." << std::endl;   
} 

如果節點包含「。」,您可以建議如何閱讀孩子嗎? ( IP地址 ) ?這裏的「nodes.test」可以工作,但「節點192.168.1.1」不起作用,因爲它包含「。」。作爲字符串?如何讓它工作?

在此先感謝。

回答

3

docs

要使用非默認'.'以外的分隔符,你需要明確構建路徑對象。 ptree的路徑類型是string_path實例化,所以引用它的最簡單方法是ptree::path_type。這樣,您就可以使用具有點在他們的鑰匙樹木

在你的情況[。]:

boost::optional< ptree& > child = pt.get_child_optional(ptree::path_type("nodes/192.168.1.1", '/')); 
+0

謝謝。我已經嘗試過,現在正在工作。 – Neel