构造一个类似于JSON文件c++的字符串
Structure a string like a JSON file c++
我有一个字符串std::string sub("{"color": "green","type": "primary"}");
。我解析它,结果是:
color:green
type:primary
我想重新组织结构,使其成为一个有效的JSON表达式,类似于以下内容:
{
"color": "yellow",
"type": "primary"
}
我知道我必须使用类似to string method
的东西,但我不知道如何做到这一点。在这之后,我想可以访问字符串的元素,比如get(color)
。注意:我的color:green, type:primary
是std::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"}
相关文章:
- 如何使用curlpp通过POST方法上传文件和json数据
- 如何在特定位置追加 json 文件
- 将 FlatBuffer 对象序列化为 JSON,而不使用其架构文件
- 如何在Visual C+++中从JSON文件中读取节点数据
- 如何将 json 数据附加到 Qt 中的现有 json 文件中
- 当前步骤:构建任务.json 文件
- 可以在JSON文件的帮助下在Qt中创建UI表单
- 将 cpprestsdk json 值对象写入文件
- 如何在 C++ 中使用提升属性树从 JSON 文件中读取对象数组
- 有没有办法从Makefile访问VS Code c_cpp_properties.json文件中的定义
- 保存json文件后如何返回文件路径
- 构造一个类似于JSON文件c++的字符串
- 使用 jsoncpp 读取 JSON 文件
- 在C++中打开 json 文件时遇到问题
- 使用 JSONCPP 将 JSON 数据增量写入文件
- Nlohmann 在不知道密钥的情况下解析 JSON 文件
- 如何使用 rapidjson 读取 json 文件并输出到 std::string?
- 比较 JSON::Value 变量中的数据,然后更新到文件
- 如何使用QJSONARRAY在QT5(C )中解析JSON文件(数组)
- 在 c++ 中读取配置文件 json 并没有停止