16

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

3 Answers 3

25

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;
}
3
  • 1
    This comment is the most up-to-date answer.
    – BFamz
    Commented Jan 14, 2021 at 7:41
  • It did not work for me. No member named contains
    – vijayst
    Commented Nov 4, 2022 at 16:59
  • Then you are using a very old version. Commented Nov 5, 2022 at 17:16
1

use find including images and candidates and check:

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

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;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.