我正在使用 C++ 代码读取 json 字符串以检索基于特定键名的值。我来自 Web API 的 json 响应示例采用如下数组格式。
[
{
"username": "123456",
"useraddress": "abc",
"data": [
{
"schedule": true,
"task": "abc",
"risk": "1",
}
],
"date": "0000-00-00"
}
]
像上面的格式是实际的响应。我必须使用键“日期”检索日期值。
我的代码片段:
{
std::stringstream jsonString;
boost::property_tree::ptree pt;
jsonString << ws2s(Info).c_str();
boost::property_tree::read_json(jsonString, pt);
std::string date = pt.get<std::string>("date");
}
上面代码段中的'Info'是包含json响应数据的wsstring。
如果手动删除 [] 方括号,我可以检索“日期”。由于是数组格式,如果不去掉括号就通过,read_json 会报错。
有人可以帮忙吗?
答案 0 :(得分:0)
是的。 Boost Property Tree 是一个属性树库,不是 JSON。
不过你很幸运,Boost 现在有一个 JSON 库https://www.boost.org/doc/libs/1_75_0/libs/json/doc/html/index.html
<块引用>注意:您的输入也不是有效的 JSON,因为 JSON 不严格允许尾随逗号。您可以使用 Boost JSON 中的选项启用它们:
#include <boost/json.hpp>
#include <iostream>
int main() {
std::string input = R"(
[
{
"username": "123456",
"useraddress": "abc",
"data": [
{
"schedule": true,
"task": "abc",
"risk": "1",
}
],
"date": "0000-00-00"
}
])";
boost::json::parse_options options;
options.allow_trailing_commas = true;
auto json = boost::json::parse(input, {}, options);
for (auto& el : json.as_array()) {
std::cout << el.at("date") << "\n";
}
}
印刷品
"0000-00-00"