使用Boost :: Ptree的JSON数组 [英] JSON Array using Boost::Ptree
问题描述
如何创建可以编码为JSON以下的boost ptree?即,我想知道如何在boost ptree中表示JSON对象的JSON数组.
[{"3":"SomeValue"}},{"40":"AnotherValue"},{"23":"SomethingElse"},{"9":"AnotherOne"},{"1":"LastOne"}]
我必须说以下链接没有答案:
演示
这是您可以做的最好的事情,假设您确实不需要数组作为文档根目录:
#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:
DEMO
Here's the best you can do, assuming you did not really need the array as document root:
#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屋!