4

I'm new to c++ and trying to use nlohmann library and I'm quite stuck. I want to modify array of objects from json.

json = 
{
    "a": "xxxx",
    "b": [{
        "c": "aaa",
        "d": [{
                "e": "yyy"
            },
            {
                "e": "sss",
                "f": "fff"
            }
        ]
    }]
}

now I want to replace e value with "example" in the above structure. Could some one help me.

I tried to loop through the json structure and was able to read the "e" value but can't replace it. I tried: `

std::vector<std::string> arr_value;
std::ifstream in("test.json");
json file = json::parse(in);

for (auto& td : file["b"])
    for (auto& prop : td["d"])
        arr_value.push_back(prop["e"]);
        //std::cout<<"prop" <<prop["e"]<< std::endl;

for (const auto& x : arr_value)
    std::cout <<"value in vector string= " <<x<< "\n";

for (decltype(arr_value.size()) i = 0; i <= arr_value.size() - 1; i++)
{
    std::string s = arr_value[i]+ "emp";
    std::cout <<"changed value= " <<s << std::endl;
    json js ;
    js = file;
    std::ofstream out("test.json");
    js["e"]= s;
    out << std::setw(4) << js << std::endl;

}
3
  • 2
    Please show your code (minimal reproducible example) Commented Jan 29, 2020 at 15:25
  • you are creating a new js and set "e" to s on that new json object. What happens when you try to modify the original json file ? Commented Jan 29, 2020 at 15:46
  • yes, you are right It only creates new "e" value and Im not able to modify the original json file, which is what I want to do. Commented Jan 29, 2020 at 15:48

1 Answer 1

5

The following appends MODIFIED to every "e"-value and writes the result to test_out.json:

#include <vector>
#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
        std::ifstream in("test.json");
        json file = json::parse(in);

        for (auto& td : file["b"])
                for (auto& prop : td["d"]) {
                        prop["e"] = prop["e"].get<std::string>() + std::string(" MODIFIED");
                }

        std::ofstream out("test_out.json");
        out << std::setw(4) << file << std::endl;
}

The prop["e"] = ... line does three things:

  • It gets the property with key "e",
  • Coerces it into a string using .get<std::string>() and appends "modified", and
  • writes back the result to prop["e"], which is a reference to the object nested in the JSON structure.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, it worked like charm and thanks for the detailed explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.