How to check if key present in nested json in c++ using nlohmann How to check if key present in nested json in c++ using nlohmann json json

How to check if key present in nested json in c++ using nlohmann


There is a member function contains that returns a bool indicating whether a given key exists in the JSON value.

Instead of

auto subjectIdIter = response.find("subject_id");if (subjectIdIter != response.end()){    cout << "it is found" << endl;}else{    cout << "not found " << endl;}

You could write:

if (response.contains("subject_id"){    cout << "it is found" << endl;}else{    cout << "not found " << endl;}


use find including images and candidates and check:

if (response["images"]["candidates"].find("subject_id") !=            response["images"]["candidates"].end())


Candidates is an array, so you just need to iterate the objects and call find.

bool found = false;for( auto c: response.at("images").at("candidates") ) {    if( c.find("subject_id") != c.end() ) {        found = true;        break;    }}