How to create empty array node using boost property_tree json parser
I am trying to create a node array in json whose output looks like this:
{
node: ["12", "13"]
}
but when the array is empty it will output this:
{
node: ""
}
this is not what i want, i need this:
{
node: []
}
How can i do this? And I don't need double quotes ("") around numbers. Can anyone please help?
My code looks like this:
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.
source to share
Boost doesn't have a JSON library. It has a library of properties (think: hierarchical configuration formats).
It specifically states that some things are not well supported:
- arrays in JSON is a hack (you can't imagine an empty array)
- all type information is lost (everything must be a JSON string)
This fits the intended application domains for Boost PropertyTree. If that doesn't fit your problem then use the JSON library.
source to share
This answer assumes that at a later stage, you are going to create your property tree string. I found a small workaround for this kind of situations. 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 characters [""]
with []
. To do this, you just need to do:
#include <boost/algorithm/string.hpp>
boost::replace_all(json_string, "[\"\"]", "[]");
This way you get a line containing
{
"node": []
}
Hope it helps.
source to share