I'm trying to create an array node in json, which output is like this:
{
node: ["12", "13"]
}
but when array is empty, it will output this:
{
node: ""
}
that's not what I want, I need this:
{
node: []
}
How can I do that ? And I don't need double quotes("") around numbers. Can anyone help ?
My code is like below:
boost::property_tree::ptree pt;
boost::property_tree::ptree array;
for (vector<int>::const_iterator iter = v.begin();
iter != v.end();
++iter)
{
boost::property_tree::ptree node;
node.put("code", *iter);
array.push_back(std::make_pair("", node));
}
pt.add_child("array", array);
Thanks for your attention.
PSA Boost 1.75.0 introduced Boost JSON; it can doe this: Live Demo
std::cout << json::object{{"node", json::array{}}};
Boost doesn't have a JSON library. It has a property-tree (think: hierarchical configuration formats) library.
documentation: http://www.boost.org/doc/libs/1_58_0/doc/html/property_tree/parsers.html#property_tree.parsers.json_parser
It specifically states that some things are not well-supported:
This suits the intended application domains for Boost PropertyTree. If it doesn't suit your problem, use a JSON library.
This answer assumes that, at a later stage, you're going to make a string of your property tree. I found a little workaround for this kind of situation. Instead of creating
{
"node": ""
}
you can easily create
{
"node": [""]
}
by doing
ptree parent_tree, children, child;
children.push_back(std::make_pair("", child));
pt.add_child("node", children);
Later, when you have a string representation of your json, you can replace the characters [""]
by []
. For this you just need to do:
#include <boost/algorithm/string.hpp>
boost::replace_all(json_string, "[\"\"]", "[]");
This way, you will end up with a string containing
{
"node": []
}
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With