使用Boost :: Ptree的JSON数组 [英] JSON Array using Boost::Ptree

查看:112
本文介绍了使用Boost :: Ptree的JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建可以编码为JSON以下的boost ptree?即,我想知道如何在boost ptree中表示JSON对象的JSON数组.

  [{"3":"SomeValue"}},{"40":"AnotherValue"},{"23":"SomethingElse"},{"9":"AnotherOne"},{"1":"LastOne"}] 

我必须说以下链接没有答案:

演示

这是您可以做的最好的事情,假设您确实不需要数组作为文档根目录:

在Coliru上直播

  #define BOOST_BIND_GLOBAL_PLACEHOLDERS#include< boost/property_tree/json_parser.hpp>#include< iostream>使用boost :: property_tree :: ptree;int main(){ptree arr;对于(自动[k,v]:{std :: pair{"3","SomeValue"}},{"40","AnotherValue"}},{"23","SomethingElse"},{"9",另一个"},{"1","LastOne"}}}{ptree元素;element.put(k,v);arr.push_back({",element});}//在文档的根目录下不能有数组...ptree doc;doc.put_child("arr",arr);write_json(std :: cout,doc);} 

打印

  {"arr":[{"3":"SomeValue"},{"40":"AnotherValue"},{"23":"SomethingElse"},{"9":另一个".},{"1":"LastOne";}]} 


How to create a boost ptree which can be encoded to below JSON? i.e. I want to know how JSON Array of JSON Objects can be represented in boost ptree..

[
{"3":"SomeValue"},
{"40":"AnotherValue"},
{"23":"SomethingElse"},
{"9":"AnotherOne"},
{"1":"LastOne"}
]

I must say the below link doesn't answer: Creating JSON arrays in Boost using Property Trees

解决方案

The link does answer it. All the answers clearly show that you should use push_back (or insert, actually), not put_child.

You also have to read past the "how to make the array" and realize that you cannot have arrays as document root.

This is a symptom of the fact that Boost Ptree is not a JSON library. It's a Property Tree library, and it supports only property trees. The limitations are documented:

https://www.boost.org/doc/libs/1_74_0/doc/html/property_tree/parsers.html#property_tree.parsers.json_parser

DEMO

Here's the best you can do, assuming you did not really need the array as document root:

Live On Coliru

#define BOOST_BIND_GLOBAL_PLACEHOLDERS 
#include <boost/property_tree/json_parser.hpp>
#include <iostream>

using boost::property_tree::ptree;

int main() {
    ptree arr;

    for (auto [k,v]: { std::pair
            {"3",  "SomeValue"},
            {"40", "AnotherValue"},
            {"23", "SomethingElse"},
            {"9",  "AnotherOne"},
            {"1",  "LastOne"} })
    {
        ptree element;
        element.put(k, v);
        arr.push_back({"", element});
    }

    // can't have array at root of doc...
    ptree doc;
    doc.put_child("arr", arr);
    write_json(std::cout, doc);
}

Prints

{
    "arr": [
        {
            "3": "SomeValue"
        },
        {
            "40": "AnotherValue"
        },
        {
            "23": "SomethingElse"
        },
        {
            "9": "AnotherOne"
        },
        {
            "1": "LastOne"
        }
    ]
}


这篇关于使用Boost :: Ptree的JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆