【发布时间】:2015-07-10 19:43:30
【问题描述】:
我正在尝试使用此代码解析 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
【问题讨论】:
-
您尝试过类似
std::stringstream ss; write_json(ss, pt2.get_child("data"));的方法吗?在您的情况下,.get_child("somelist").get_child("data")或e.get_child("data").. 取决于您要在代码中的哪个位置使用它。 -
正在做 write_json(ss, pt2.get_child("data"));不会导致此类节点错误:-)
-
嗯?刚刚在这里尝试过,并作为一种魅力。在打印时间戳之后并添加这些行:
ptree d = e.second.get_child("data"); std::stringstream s1; write_json(s1, d); std::cout <<s1.str << std::endl;。 Demo Link