gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:13:41 24 4
gpt4 key购买 nike

我在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com