Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a below json data:

{
    "images": [
        {
            "candidates": [
                {
                    "confidence": 0.80836,
                    "enrollment_timestamp": "20190613123728",
                    "face_id": "871b7d6e8bb6439a827",
                    "subject_id": "1"
                }
            ],
            "transaction": {
                "confidence": 0.80836,
                "enrollment_timestamp": "20190613123728",
                "eyeDistance": 111,
                "face_id": "871b7d6e8bb6439a827",
                "gallery_name": "development",
                "height": 325,
                "pitch": 8,
                "quality": -4,
                "roll": 3,
                "status": "success",
                "subject_id": "1",
                "topLeftX": 21,
                "topLeftY": 36,
                "width": 263,
                "yaw": -34
            }
        }
    ]
}

I need to check if subject_id is present in the above json data or not. For this I did below:

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

}
else
{
    cout << "not found " << endl;
}

How can I resolve this. Thanks

like image 534
S Andrew Avatar asked Jun 18 '19 11:06

S Andrew


3 Answers

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;
}
like image 184
Niels Lohmann Avatar answered Oct 20 '22 13:10

Niels Lohmann


use find including images and candidates and check:

if (response["images"]["candidates"].find("subject_id") != 
           response["images"]["candidates"].end())
like image 27
ΦXocę 웃 Пepeúpa ツ Avatar answered Oct 20 '22 11:10

ΦXocę 웃 Пepeúpa ツ


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;
    }
}
like image 22
Jorge Bellon Avatar answered Oct 20 '22 12:10

Jorge Bellon