0

I have been using the nlohmann json library for a while, but i found myself with a problem recently. I have a vector of indexes for an object:

vector<string> indexes = {"value1", "subval"}; // etc

and I want to do something like this:

json myObj = "{\"value1\":{}}"_json;
myObj["value1"]["subval"] = "test";

How can i do this?

I tried this:

json myObj = "{\"value1\":{}}"_json;
json ref = myObj;

for (string i : indexes) {
  ref = ref[i];
}

myObj = ref;

but this will not work because it is not accessing nested elements, it is just setting the object to be the nested value.

Ank i zle
  • 2,089
  • 3
  • 14
  • 36

1 Answers1

1

json ref = myObj;

When you do this you should realise that ref is not a reference or a pointer, whatever you wanted. It's a copy.

Solution: Try using a reference_wrapper instead.

     vector<string> indexes = {"value1", "subval"};                                                                                                                                                         
     json myObj;                                                                                                                                                                                            
     auto ref = std::ref(myObj);                                                                                                                                                                            

     for (string i : indexes) {                                                                                                                                                                             
         ref = ref.get()[i];                                                                                                                                                                                
     }                                                                                                                                                                                                      
     ref.get() = "test";                                                                                                                                                                                                   
     std::cout << myObj << std::endl;

Or instead of reference_wrapper, you can use a pointer as well. Your wish. A json& ref would obviously not work - you cannot reassign a reference, hence a reference_wrapper instead.

theWiseBro
  • 1,439
  • 12
  • 11