Search code examples
c++arraysjsonboost

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.


Solution

  • 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.