Search code examples
c++nestednlohmann-json

c++ nlohmann json - how to test nested object is existent or empty


I have a nested Json like this:

   string strJson = "{
  "Header":

    {"Version":"V0.00.01","ID":"1000","Name":"SetEnvValues"}


  ,
  "Data":

    {"Temp":0.00,"rH":0.00,"CO2":0.00,"O2":0.00 }



}";

Now I want to test if there is an Element "rH" existent. For example, if I only have in the Data Objekt one value "Temp", how can I test which values are existent? Is this possible without exception handling?

{
"Header":

{"Version":"V0.00.01","ID":"1000","Name":"SetEnvValues"}


,
"Data":

{"Temp":0.00 }



}

I tried it with count, but it seems this wont work for nested objects:

jsonReceivedEnvValues = json::parse(strJson);
int count = jsonReceivedEnvValues["Data"].count("Bla");

This returns always one, I think because it only tests the "Data" Object, and not the deeper nested ones.


Solution

  • It can be done with jsonReceivedEnvValues["Data"].count("Bla"). Make sure that you don't accidentally create the object you're looking for; for instance, jsonReceivedEnvValues["Data"]["Bla"].is_null(); creates an object ["Bla"] in ["Data"]