property_tree获取字符串形式的数组值

property_tree get array value as String

本文关键字:数组 字符串 tree 获取 property      更新时间:2023-10-16

我想用boostsproperty_tree解析json文件/字符串,但我不希望将子树解析成数组,而是希望它保留为字符串,用于另一个只处理json字符串的现有函数。

我希望以下例子就足够了:


example.json

{
"type": "myType",
"colors": {
"color0":"red",
"color1":"green",
"color2":"blue"
}
}

main.cpp

std::stringstream ss("example.json");
ptree pt;
read_json(ss, pt);
std::string sType = pt.get("type", "");
std::string sColors = pt.get<std::string>("colors");
std::cout << "sType: " << sType << std::endl; // sType: myType
std::cout << "sColors: " << sColors << std::endl; // sColors: {"color0":"red", "color1":"green", "color2":"blue"}

我尝试过几个函数,例如pt.get_child("colors")只会返回另一个ptree,而pt.get_value<std::string>("colors")会返回一个空字符串("")

所需的输出如下所示:

sColors: {"color0":"red", "color1":"green", "color2":"blue"}

sColors: {"color0":"red", "color1":"green", "color2":"blue"}

有没有一种方法可以获得sColors所需的输出?

我比预期更快地找到了一个可能的解决方案,下面的代码将提供令人满意的答案:

std::stringstream os;
write_json(os, pt.get_child("colors"), false);
std::string sColors = os.str();
std::cout << "sColors: " << sColors << std::endl;

如果有更优雅的解决方案,也可以随意发布!