gpt4 book ai didi

c++ - 将 json 对象转换为字符串 boost

转载 作者:行者123 更新时间:2023-11-27 23:57:18 26 4
gpt4 key购买 nike

我是 stackoverflow 的新手,抱歉,如果我有任何错误,请纠正我,如果我错了。我在 boost 中做了很多关于 json 解析器和 xml 解析器的研究。我想做的是,假设我有一个如下所示的 json

      {
"topology_1":{
"clnt_id":"aldgdsgsd",
"sensors":{
"num_sensors":"6",
"sensor_1":{
"time_interval":"5#15",
"min_bound":"",
"max_bound":"54",
"anomaly":"2%",
"anomaly_window":"70",
"jump":"10",
"topic":"sense/thubrahali/temp",
"qos":"1"
}
}
}
}

我想将从 boost jsonparser 获取的“topology”的值转换为字符串,以便将它存储在容器中的某个地方供以后使用。现在我不能真正直接通过 theboost 库获取值,因为它将它视为一个 json 对象。我应该如何将此值转换为字符串。

最佳答案

通常需要注意的是,boost 没有 JSON 库。如果您留在 Boost Property Tree 提供的子集中,您可以:

std::string as_json_string(ptree const& pt) {
std::ostringstream oss;
write_json(oss, pt);
return oss.str();
}

演示

Live On Coliru

#include <boost/property_tree/json_parser.hpp>
#include <iostream>
using boost::property_tree::ptree;

std::string as_json_string(ptree const& pt) {
std::ostringstream oss;
write_json(oss, pt);
return oss.str();
}

int main() {
std::istringstream iss(R"({
"topology_1": {
"clnt_id": "aldgdsgsd",
"sensors": {
"num_sensors": "6",
"sensor_1": {
"time_interval": "5#15",
"min_bound": "",
"max_bound": "54",
"anomaly": "2%",
"anomaly_window": "70",
"jump": "10",
"topic": "sense/thubrahali/temp",
"qos": "1"
}
}
}
})");

ptree document;
read_json(iss, document);

// and back to string
std::string topology_1 = as_json_string(document.get_child("topology_1"));

std::cout << topology_1;
}

打印

{
"clnt_id": "aldgdsgsd",
"sensors": {
"num_sensors": "6",
"sensor_1": {
"time_interval": "5#15",
"min_bound": "",
"max_bound": "54",
"anomaly": "2%",
"anomaly_window": "70",
"jump": "10",
"topic": "sense\/thubrahali\/temp",
"qos": "1"
}
}
}

关于c++ - 将 json 对象转换为字符串 boost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41652564/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com