C ++ boost ptree rename key

In the boost property tree, I would like to rename the key, for example a.b.c2

to a.b.c3

.

One way is to remove the node and put a copy of it with a different name. The problem is that node is placed at the end of its other siblings. I prefer to save the order. How can I fix this code?

#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/algorithm/string/predicate.hpp>

using namespace boost::property_tree;

void print(const ptree &p)
{
    json_parser::write_json(std::cout, p);
}

int main()
{
    ptree pt0;

    pt0.put("a.b.c1",4);
    pt0.put("a.b.c2.e1",4);
    pt0.put("a.b.c4",2);
    pt0.put("a.d",4);
    pt0.put("k.m",4);
    pt0.put("k.n.as",4);

    std::string key_parent="a.b";
    std::string full_key="a.b.c2";
    std::string full_key2="a.b.c3";
    ptree node=pt0.get_child(full_key);
    pt0.get_child(key_parent).erase("c2");
    pt0.put_child(full_key2,node);

    print(pt0);

    return 0;
}

      

Results: (

// before:
{
    "a": {
        "b": {
            "c1": "4",
            "c2": {
                "e1": "4"
            },
            "c4": "2"
        },
        "d": "4"
    },
    "k": {
        "m": "4",
        "n": {
            "as": "4"
        }
    }
}


// after:
{
    "a": {
        "b": {
            "c1": "4",
            "c4": "2",
            "c3": {
                "e1": "4"
            }
        },
        "d": "4"
    },
    "k": {
        "m": "4",
        "n": {
            "as": "4"
        }
    }
}

      

+3


source to share


1 answer


You can use insert

and for this iterator

.



ptree &child = pt0.get_child("a.b");
ptree::iterator it = child.to_iterator(child.find("c2"));
child.insert(it, make_pair("c3", it->second));
child.erase(it);

      

+2


source







All Articles