Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a convenient way to erase a node from a property tree, preserving its child nodes?

I want to delete a node from a boost property tree, but I want to preserve its children and connect them to the parent of the deleted node (i.e. to their grandparent node). Is there an elegant way to achieve this?

like image 852
Marste Avatar asked Nov 23 '25 00:11

Marste


1 Answers

This might be the most efficient way to move the grandchildren:

std::move(middle.begin(), middle.end(), back_inserter(parent));

Full sample

Live On Coliru

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

using boost::property_tree::ptree;
using boost::property_tree::read_json;
using boost::property_tree::write_json;

int main() {

    std::istringstream iss(R"({ "a" : { "middle" : { "a1":1, "a2":2, "a3":3 }, "more":"stuff" } })");
    ptree pt;
    read_json(iss, pt);

    auto& parent = pt.get_child("a");
    auto& middle = pt.get_child("a.middle");

    std::move(middle.begin(), middle.end(), back_inserter(parent));
    parent.erase("middle");

    write_json(std::cout, pt);

}

Sample json output:

{
    "a": {
        "more": "stuff",
        "a1": "1",
        "a2": "2",
        "a3": "3"
    }
}
like image 128
sehe Avatar answered Nov 24 '25 16:11

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!