【问题标题】:Parse JSON array value as std::string using Boost使用 Boost 将 JSON 数组值解析为 std::string
【发布时间】:2015-07-10 19:43:30
【问题描述】:

我正在尝试使用此代码解析 std::string JSON 字符串:

        std::string ss = "{ \"id\" : \"abc123\", \"number\" : \"0123456789\", \"somelist\" : [{ \"timestamp\" : \"May 1, 2015\" , \"data\" : { \"description\" : \"some description\", \"value\" : \"100.000000\" } }] }";

        ptree pt2;
        std::istringstream is(ss);
        read_json(is, pt2);
        std::string _id = pt2.get<std::string>("id");
        std::string _number = pt2.get<std::string>("number");
        std::string _list = pt2.get<std::string>("somelist"); 


        for (auto& e : pt2.get_child("somelist")) {
            std::cout << "timestamp: " << e.second.get<std::string>("timestamp") << "\n";
            for (auto& e1 : pt2.get_child("data")){ // not working
                std::cout << "description: " << e1.second.get<std::string>("description") << "\n";
                std::cout << "value: " << e1.second.get<std::string>("amount") << "\n";
            }
        }

虽然我的目标不是打印子项(也不是将 JSON 字符串转换为 C++ 数组)。上面的代码不起作用。

我想知道如何获取data 的值而不是数组或其他东西,就像[{ "timestamp" : "May 1, 2015" , "data" : { "description" : "some description", "value" : "100.000000" } }] 这样的字符串

只需要 JSON 数组原样作为 std::string

【问题讨论】:

  • 您尝试过类似std::stringstream ss; write_json(ss, pt2.get_child("data")); 的方法吗?在您的情况下,.get_child("somelist").get_child("data")e.get_child("data").. 取决于您要在代码中的哪个位置使用它。
  • 正在做 write_json(ss, pt2.get_child("data"));不会导致此类节点错误:-)
  • 嗯?刚刚在这里尝试过,并作为一种魅力。在打印时间戳之后并添加这些行:ptree d = e.second.get_child("data"); std::stringstream s1; write_json(s1, d); std::cout &lt;&lt;s1.str &lt;&lt; std::endl;Demo Link

标签: c++ boost


【解决方案1】:

boost/property_tree/json_parser.hpp 实现了write_json,正如您所料,它是read_json 的倒数。由于ptree 将数组存储为具有空键的对象,为了实现您想要的表示,您将遍历pt2.get_child("somelist") 中的顶级ptrees,对它们中的每一个调用write_json 并将这些表示格式化为你愿意。

for(auto const& node : pt2.get_child("somelist"))
 write_json(std::cout, node.second);

Coliru Demo.

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 2013-06-12
    • 2013-08-27
    • 2022-11-19
    相关资源
    最近更新 更多