Search code examples
c++nlohmann-json

access json array values in c++


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;

}

Solution

  • 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.