c++ - 使用 boost property_tree 创建 json 数组

标签 c++ json boost properties tree

我在使用 C++ 中的 boost 库和属性树创建 json 数组时遇到了麻烦。

我引用了this线程,尤其是这部分

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"
        }
    ]
}

但是如果我只想实现一个没有任何对象包含它的简单数组,我该怎么办呢?像这样:

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

非常感谢。

最佳答案

关于 JSON 支持的 Boost 文档只有几行:

http://www.boost.org/doc/libs/1_63_0/doc/html/property_tree/parsers.html#property_tree.parsers.json_parser

The property tree dataset is not typed, and does not support arrays as such. Thus, the following JSON / property tree mapping is used:

  • JSON objects are mapped to nodes. Each property is a child node.
  • JSON arrays are mapped to nodes. Each element is a child node with an empty name. If a node has both named and unnamed child nodes, it cannot be mapped to a JSON representation.
  • JSON values are mapped to nodes containing the value. However, all type information is lost; numbers, as well as the literals "null", "true" and "false" are simply mapped to their string form.
  • Property tree nodes containing both child nodes and data cannot be mapped.

JSON round-trips, except for the type information loss.

突出显示我的

关于c++ - 使用 boost property_tree 创建 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43324370/

相关文章:

angularjs - 如何使用 $http.get 显示数据

c++ - 每个类(class)都有不同的 boost 日志接收器

c++ - 无法在 Linux 上进行回车

c++ - 散列溢出

c++ - 在 C++ 中,在对象内分配多个数据时,堆栈分配是否更有效? A_Heap 类在下面的程序中效率会降低吗?

c++ - 我应该使用哪个数组/列表?

mysql - Json feed blob 图像在 UIImage swift 中显示

javascript - 了解节点以及如何追加

c++ - 为什么在使用 boost::asio 为 STDIN/STDOUT 管道传输到程序时,read() 会因 EAGAIN 失败?

android - CrystaX 与 clang++ 和 libc++ 与 boost 和 icu 发生链接错误