如何创建可编码到JSON以下的boost ptree?也就是说,我想知道如何用boost ptree来表示JSON对象的JSON数组。
[
{"3":"SomeValue"},
{"40":"AnotherValue"},
{"23":"SomethingElse"},
{"9":"AnotherOne"},
{"1":"LastOne"}
]我必须说下面的链接没有回答:使用属性树在Boost中创建JSON数组
发布于 2020-09-23 22:22:55
链接确实回答了这个问题。所有答案都清楚地表明,您应该使用push_back (实际上是insert ),而不是put_child。
您还必须阅读“如何制作数组”,并意识到不能将数组作为文档根。
这是Boost Ptree是而不是JSON库的一个症状。它是一个属性树库,它只支持属性树。这些限制已记录在案:

演示
以下是您能做的最好的事情,假设您并不真正需要将数组作为文档根:
住在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);
}打印
{
"arr": [
{
"3": "SomeValue"
},
{
"40": "AnotherValue"
},
{
"23": "SomethingElse"
},
{
"9": "AnotherOne"
},
{
"1": "LastOne"
}
]
}https://stackoverflow.com/questions/64016751
复制相似问题