12

我有以下 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上述 json 数据中是否存在。为此,我在下面做了:

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

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

我该如何解决这个问题。谢谢

4

3 回答 3

13

有一个成员函数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;
}
于 2019-06-30T11:05:03.287 回答
1

Candidates 是一个数组,所以你只需要迭代对象并调用 find。

bool found = false;
for( auto c: response.at("images").at("candidates") ) {
    if( c.find("subject_id") != c.end() ) {
        found = true;
        break;
    }
}
于 2019-06-18T12:09:43.730 回答
1

使用 find 包括图像和候选人并检查:

if (response["images"]["candidates"].find("subject_id") != 
           response["images"]["candidates"].end())
于 2019-06-18T11:39:27.627 回答