Skip to content

How to rename a key during looping? #893

Closed

Description

@gestern

I want to change key within a loop. Is it possible? How? For example, having a code:

for (auto& a : json::iterator_wrapper(b.value())) {
                auto aname = a.key();

How to rename a.key()? Looks like it's not described itself by documentation.

Activity

  1. nlohmann commented on Dec 27, 2017

    @nlohmann
    Owner

    This is not possible. JSON objects are stored internally as std::map. Their keys are const while iterating.

  2. gestern commented on Dec 27, 2017

    @gestern
    Author

    Thanks, so just to understand, in general, is there any chance to easy rename a key, means without using a pair remove/insert? Like rapidjson:

    it->name.SetString ("new key", d.GetAllocator());
  3. nlohmann commented on Dec 28, 2017

    @nlohmann
    Owner

    You can use this function:

    #include <iostream>
    #include "json.hpp"
    
    using json = nlohmann::json;
    
    void change_key(json &object, const std::string& old_key, const std::string& new_key)
    {
        // get iterator to old key; TODO: error handling if key is not present
        json::iterator it = object.find(old_key);
        // create null value for new key and swap value from old key
        std::swap(object[new_key], it.value());
        // delete value at old key (cheap, because the value is null after swap)
        object.erase(it);
    }
    
    int main()
    {
        json j;
        j["foo"] = "value";
        
        std::cout << j << std::endl;
    
        change_key(j, "foo", "bar");
        
        std::cout << j << std::endl;
    }

    Output:

    {"foo":"value"}
    {"bar":"value"}

    I just adjusted code from https://stackoverflow.com/a/5743682/266378.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    solution: proposed fixa fix for the issue has been proposed and waits for confirmation

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions