构造一个类似于JSON文件c++的字符串

Structure a string like a JSON file c++

本文关键字:文件 JSON c++ 字符串 类似于 一个      更新时间:2023-10-16

我有一个字符串std::string sub("{"color": "green","type": "primary"}");。我解析它,结果是:

color:green
type:primary

我想重新组织结构,使其成为一个有效的JSON表达式,类似于以下内容:

{
"color": "yellow",
"type": "primary"
}

我知道我必须使用类似to string method的东西,但我不知道如何做到这一点。在这之后,我想可以访问字符串的元素,比如get(color)。注意:我的color:green, type:primarystd::map<std::string,string> keyVal类型。

您可以使用boost json解析器

https://www.boost.org/doc/libs/1_65_1/doc/html/property_tree.html

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
using namespace boost::property_tree;
int main()
{
try{
ptree pt;
json_parser::read_json("file.json", pt); // <- invalid will be caught
std::string color = pt.get<std::string>("color");
std::string something = pt.get<std::string>("root.path.to.key");
}catch(...)
{
std::cout<<"invalid!"<<std::endl;
}
return 0;
}

对于配置样式的数据,请选择write_info和read_info。

如果您更喜欢使用字符串而不是文件,那么对于字符串到json的属性,请遵循

const std::string json="{"color": "green","type": "primary"}";
ptree pt;
std::istringstream i_str(json);
read_json(i_str, pt);

json属性转换为字符串:

const ptree pt=...;
std::ostringstream buf; 
write_json(buf, pt, false);
std::string json = buf.str(); // {"foo":"bar"}