使用 boost::property_tree::ptree 读取配置文件

近期有一需求:需要一个地址配置项,同时提供一个地址列表,读取的地址如果在地址列表内,则自动替换,大概的 json 配置文件如下:

{
	"host_list" : {
		"BDC" : "chn.xxx.com",
		"MDC" : "alpha01.xxx.com",
		"vm" : "10.209.9.83",
		"local" : "127.0.0.1"
	},
	"host" : { "addr": "BDC", "port": 7777 }
}
读到 host.addr 为 BDC 时,替换成 chn.xxx.com;但还需要支持不在 host_list 内的地址

使用 boost::optional 的实现如下:

	using boost::property_tree::ptree;
	ptree pt;
	read_json("./xxx/config.json", pt);

	std::string host = pt.get<std::string>("host.addr");
	boost::optional<ptree&> mapedHostAddr(pt.get_child_optional(std::string("host_list.") + host));
	if( mapedHostAddr )
		host = mapedHostAddr.get().data();
还可以使用带 default_value 的重载函数,这样可能更简单一些:
host = pt.get<std::string>(std::string("host_list.") + host, host);



版权声明:本文为robothn原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。