使用属性树在加速创建JSON阵列 [英] Creating JSON arrays in Boost using Property Trees

查看:124
本文介绍了使用属性树在加速创建JSON阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个使用升压财产树的JSON阵列。

I'm trying to create a JSON array using boost property trees.

的<一个href=\"http://www.boost.org/doc/libs/1_49_0/doc/html/boost_propertytree/parsers.html#boost_propertytree.parsers.json_parser\">documentation说:JSON数组被映射到节点的每个元素与空名称的子节点。

The documentation says: "JSON arrays are mapped to nodes. Each element is a child node with an empty name."

所以我想创建一个空的名称的属性树,然后调用 write_json(...)来获取数组的。但是,文件并没有告诉我如何创建无名子节点。我试图 ptree.add_child(,值),但这个收益率:

So I'd like to create a property tree with empty names, then call write_json(...) to get the array out. However, the documentation doesn't tell me how to create unnamed child nodes. I tried ptree.add_child("", value), but this yields:

Assertion `!p.empty() && "Empty path not allowed for put_child."' failed

文档似乎并没有针对这一点,至少不会以任何方式我可以找出。谁能帮助?

The documentation doesn't seem to address this point, at least not in any way I can figure out. Can anyone help?

推荐答案

简单阵列:

#include <boost/property_tree/ptree.hpp>
using boost::property_tree::ptree;

ptree pt;
ptree children;
ptree child1, child2, child3;

child1.put("", 1);
child2.put("", 2);
child3.put("", 3);

children.push_back(std::make_pair("", child1));
children.push_back(std::make_pair("", child2));
children.push_back(std::make_pair("", child3));

pt.add_child("MyArray", children);

write_json("test1.json", pt);

结果:

{
    "MyArray":
    [
        "1",
        "2",
        "3"
    ]
}

在数组对象:

ptree pt;
ptree children;
ptree child1, child2, child3;


child1.put("childkeyA", 1);
child1.put("childkeyB", 2);

child2.put("childkeyA", 3);
child2.put("childkeyB", 4);

child3.put("childkeyA", 5);
child3.put("childkeyB", 6);

children.push_back(std::make_pair("", child1));
children.push_back(std::make_pair("", child2));
children.push_back(std::make_pair("", child3));

pt.put("testkey", "testvalue");
pt.add_child("MyArray", children);

write_json("test2.json", pt);

结果:

{
    "testkey": "testvalue",
    "MyArray":
    [
        {
            "childkeyA": "1",
            "childkeyB": "2"
        },
        {
            "childkeyA": "3",
            "childkeyB": "4"
        },
        {
            "childkeyA": "5",
            "childkeyB": "6"
        }
    ]
}

希望这有助于

这篇关于使用属性树在加速创建JSON阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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