我正在尝试使用以下代码解析 std::string JSON 字符串:
std::string ss = "{ \"id\" : \"abc123\", \"number\" : \"0123456789\", \"somelist\" : [{ \"timestamp\" : \"May 1, 2015\" , \"data\" : { \"description\" : \"some description\", \"value\" : \"100.000000\" } }] }";
ptree pt2;
std::istringstream is(ss);
read_json(is, pt2);
std::string _id = pt2.get<std::string>("id");
std::string _number = pt2.get<std::string>("number");
std::string _list = pt2.get<std::string>("somelist");
for (auto& e : pt2.get_child("somelist")) {
std::cout << "timestamp: " << e.second.get<std::string>("timestamp") << "\n";
for (auto& e1 : pt2.get_child("data")){ // not working
std::cout << "description: " << e1.second.get<std::string>("description") << "\n";
std::cout << "value: " << e1.second.get<std::string>("amount") << "\n";
}
}
尽管我的目标不是打印子项(也不是将 JSON 字符串转换为 C++ 数组)。上面的代码不起作用。
我想知道如何获取 data
的值,而不是数组或其他东西,就像这样的字符串 [{ "timestamp": "May 1, 2015", "data ": { "description": "some description", "value": "100.000000"} }]
只需要 JSON 数组作为 std::string
最佳答案
boost/property_tree/json_parser.hpp
实现了 write_json
,如您所料,它是 read_json
的逆函数。由于 ptree
将数组存储为具有空键的对象,为了实现您想要的表示,您将遍历 pt2.get_child( “somelist”)
,对它们中的每一个调用 write_json
并根据需要格式化这些表示。
for(auto const& node : pt2.get_child("somelist"))
write_json(std::cout, node.second);
关于c++ - 使用 Boost 将 JSON 数组值解析为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31349039/