【问题标题】:Structure a string like a JSON file c++ [closed]像JSON文件c ++一样构造字符串[关闭]
【发布时间】:2018-07-16 08:59: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 类型。

【问题讨论】:

  • 他们有大量的 json 库可以为你做这件事,这不是一件容易的事。
  • “我解析它,结果是”告诉我们你是怎么做的,我们猜不出你的实现
  • 请注意,您可以使用 RAW 字符串,因此您无需转义 " 字符。见en.cppreference.com/w/cpp/language/string_literal
  • C++ json 解析器列表可以在这里找到:json.org

标签: c++ json string dictionary


【解决方案1】:

您可以使用 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_inforead_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"}

【讨论】:

  • 您需要详细说明。 “boost::write_info”通过“std::wostringstream”等
  • 它被搁置了(为什么?)。但是:wostringstream str; write_json(str,pt); cout
  • @Red.Wave,这个问题对我来说有点模糊。但是非常感谢您提及这一点。
  • 欢迎您。在你不在的情况下,这可能是我的回答。我猜OP需要字符串而不是文件的输出。因此,更通用的答案将是涉及 iostream 而不是文件名的答案。
猜你喜欢
  • 2017-08-05
  • 1970-01-01
  • 1970-01-01
  • 2017-02-18
  • 2010-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-07
相关资源
最近更新 更多