Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create empty array node using boost property_tree of json parser

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.

like image 911
mkdym Avatar asked Jun 05 '15 09:06

mkdym


2 Answers

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:

  • arrays in JSON are a hack (you cannot represent the empty array)
  • all type information is lost (everything needs to be JSON string)

This suits the intended application domains for Boost PropertyTree. If it doesn't suit your problem, use a JSON library.

like image 193
sehe Avatar answered Oct 24 '22 02:10

sehe


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.

like image 44
BrunoLogan Avatar answered Oct 24 '22 04:10

BrunoLogan