Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to rename a key during looping? #893

Closed
gestern opened this issue Dec 25, 2017 · 3 comments
Closed

How to rename a key during looping? #893

gestern opened this issue Dec 25, 2017 · 3 comments
Labels
solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@gestern
Copy link

gestern commented Dec 25, 2017

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.

@nlohmann
Copy link
Owner

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

@gestern
Copy link
Author

gestern commented Dec 27, 2017

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());

@gestern gestern closed this as completed Dec 27, 2017
@gestern gestern reopened this Dec 27, 2017
@gestern gestern closed this as completed Dec 28, 2017
@nlohmann
Copy link
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.

@nlohmann nlohmann added the solution: proposed fix a fix for the issue has been proposed and waits for confirmation label Dec 28, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

2 participants