Boost JSON解析器和IP地址

Boost JSON parser and ip address

本文关键字:IP 地址 JSON Boost      更新时间:2023-10-16

我想获取具有IP地址的节点的子节点。以下是我正在使用的参考JSON格式和代码。

{  
"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"将起作用,但" nodes.192.168.1.1"不起作用,因为它包含"。作为字符串?如何使其工作?

预先感谢。

来自文档:

要使用默认'.'以外的分离器字符,您需要明确构造路径对象。ptree的路径类型是string_path的实例化,因此最简单的参考方法是ptree::path_type。这样,您可以使用键中有点的树[。]

在您的情况下:

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