Json: Unable to update a value for a nested(multi-level) json file

Created on 8 Nov 2018  ·  9Comments  ·  Source: nlohmann/json

  • What is the issue you have?

  • Please describe the steps to reproduce the issue. Can you provide a small but working code example?

  • What is the expected behavior?

  • And what is the actual behavior instead?

  • Which compiler and operating system are you using? Is it a supported compiler?

  • Did you use a released version of the library or the version from the develop branch?

  • If you experience a compilation error: can you compile and run the unit tests?

question proposed fix

All 9 comments

I am trying to update a key in a nested json(sample json below) e.g. "user_name" to value "abc". I am unable to update the value using the iterator. Is there any function which would enable me to update the value?? Does the push_back or something already implements it?

{
    "server": {
        "hostname": "192.168.xxx.xxx",
        "port": 443,
        "password": "632a1aaa-407f",
        "user_name": "xyz"
    }
}

code snippet-

void myIterator(json& j, const string configParam) {
    string res = "";
    for (auto& it : j.items()){
        if (it.value().is_structured()) {
            for (auto& it_meta : it.value().items()) {
                std::cout << "\t" << it_meta.key() << "  " << it_meta.value() << std::endl;
                if (configParam.compare(it_meta.key()) == 0) {
                    it_meta.value().**push_back**(configParam,"abc");
                    break;
                }
            }
        }
        else {
            std::cout << "\t" << it.key() << "  " << it.value() << std::endl;
        }
    }
}

So you want to achieve something like server["username] = "abc"; with iterators?

Yes , but the end user will only give the key and the parent tree “server” will not not be passed.

So you want to achieve something like server["username] = "abc"; with iterators?

Is that already being done in other ways ? I dont want to necessarily use iterators . Something that traverses the nested objects searches and adds/updates the key:values.

You can assign to it.value(), so code like

if (it.key() == "username")
  el.value() = "abc";

should work.

Furthermore, https://stackoverflow.com/a/46630394/266378 could be helpful.

Thanks Neils. Will try this out.

You can assign to it.value(), so code like

if (it.key() == "username")
  el.value() = "abc";

should work.

Furthermore, https://stackoverflow.com/a/46630394/266378 could be helpful.

Thanks for the prompt response! This works to update the value if the Key is found.
Please let me also know how to add a new key:value pair if the Key is not found.

Just like in a std::mal.

Just like in a std::map.

Was this page helpful?
0 / 5 - 0 ratings