property_tree获取字符串形式的数组值
property_tree get array value as String
我想用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;
如果有更优雅的解决方案,也可以随意发布!
相关文章:
- 使用 jsoncpp 解析 json 数组字符串
- C++ 对象数组字符串输入在控制台上不起作用
- 插入了 C++ 数组字符串数据,但在显示输出时不显示
- 无法区分 JSON 对象/数组/字符串
- 为什么数组(字符串类型)的大小是 24 字节,带有单个空格元素
- 如何使用数组字符串进行输入验证
- (C++) 打印字符数组字符串的单词时出现问题
- 使用Back_inserter从任何位置的输入字符中使用Back_inserter进行过滤数组字符串
- C 函数反转字符数组字符串
- 如何在 c++ 中创建数组(字符串 [] )的向量
- 如何返回数组字符串的指针
- char数组字符串混淆
- 如何从字符数组字符串中提取空格
- 是否可以将 Bitset<8> 的值复制到数组字符串而不转换它们?
- C++数组字符串函数
- 如何在函数中操作字符数组(字符串)的指针,该指针在C / C ++中作为参数传递
- visual将音频文件存储到数组/字符串流C++中
- c++在char数组(字符串)上将what替换为
- 将数组字符串转换为intger c++(初学者)
- 需要设置数组字符串长度,使其恰好为13