0

I have a sample nlohmann json object here. I would like to replace all the "onClick" to the "Click". please bear in mind that this a sample only. The object contains many json arrays inside each other.

{
  "menu": {
    "id": "file",
    "name": "File",
    "popup": {
      "menuitem": [
        {
          "name": "New",
          "onclick": "CreateDoc()"
        },
        {
          "name": "Open",
          "onclick": "OpenDoc()"
        },
        {
          "name": "Save",
          "onclick": "SaveDoc()"
        },
        {
          "toy": [
            {
              "value": "toyA",
              "onclick": "CreateDoc()"
            },
            {
              "value": "toyB",
              "onclick": "OpenDoc()"
            }
          ]
        }
      ]
    }
  }
}

this is what I tried my self:

auto change_key = [](nlohmann::json &object, const std::string& old_key, const std::string& new_key) 
{    
    json::iterator it = object.find(old_key);
    while(it != object.end()){
        std::swap(object[new_key], it.value());
        object.erase(it);
        it = object.find(old_key);
    }
};
H'H
  • 1,638
  • 1
  • 15
  • 39
  • Looks like your solution attempt is based on https://github.com/nlohmann/json/issues/893#issuecomment-354266107. You should include its link in your question too. The [accepted answer](https://stackoverflow.com/a/44883472/7670262) on the linked [SO thread](https://stackoverflow.com/questions/5743545/what-is-the-fastest-way-to-change-a-key-of-an-element-inside-stdmap) uses [`std::map::extract`](https://en.cppreference.com/w/cpp/container/map/extract). You might want to look at that. – Azeem Jun 01 '23 at 06:52
  • 1
    Thanks, The point is that I have multiple "onClick" key. I am not sure if we can have multiple duplicate key in map and also my situation is nested. but for the part of replacing that is a good solution. – H'H Jun 06 '23 at 13:50

1 Answers1

0

here is how I solved my problem, However more elegant solution is always welcomed.

void recursive_iterate (nlohmann::json& j, const std::string& old_key, const std::string& new_key)

{

auto change_key = [&](nlohmann::json &object) 

{    

    json::iterator it = object.find(old_key);

    // get iterator to old key; TODO: error handling if key is not present

    while(it != object.end()){

        std::swap(object[new_key], it.value());

        object.erase(it);

        it = object.find(old_key);

    }

};  

for(auto it = j.begin(); it != j.end(); ++it)

{

    change_key(*it);

    if (it->is_structured())

    {

        recursive_iterate(*it, old_key, new_key);

    }

}

}; 
H'H
  • 1,638
  • 1
  • 15
  • 39