如何使用Nlohmann检查C ++中嵌套json中是否存在密钥

时间:2019-06-18 11:32:30

标签: c++ json nlohmann-json

我有一个下面的json数据:

include

我需要检查以上json数据中是否存在{ "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 } } ] } 。为此,我在下面做了:

subject_id

我该如何解决。谢谢

3 个答案:

答案 0 :(得分:1)

有一个成员函数contains,它返回一个bool来指示JSON值中是否存在给定密钥。

代替

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

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

您可以写:

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

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

答案 1 :(得分:0)

使用包含图像和候选对象的查找并检查:

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

答案 2 :(得分:0)

候选对象是一个数组,因此您只需要迭代对象并调用find。

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