如何使用nlohmann检查C++中嵌套json中是否存在键

S A*_*rew 12 c++ json nlohmann-json

我有以下 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
            }
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我需要检查subject_id上面的json数据中是否存在。为此,我在下面做了:

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

}
else
{
    cout << "not found " << endl;
}
Run Code Online (Sandbox Code Playgroud)

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

Nie*_*ann 13

有一个成员函数contains返回一个bool指示 JSON 值中是否存在给定键。

代替

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

}
else
{
    cout << "not found " << endl;
}
Run Code Online (Sandbox Code Playgroud)

你可以写:

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

}
else
{
    cout << "not found " << endl;
}
Run Code Online (Sandbox Code Playgroud)


ΦXo*_*a ツ 1

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

if (response["images"]["candidates"].find("subject_id") != 
           response["images"]["candidates"].end())
Run Code Online (Sandbox Code Playgroud)

  • 为什么?因为编写代码的开发人员建议这样做:https://github.com/nlohmann/json/issues/1000#issuecomment-371760982 (3认同)