如何使用nlohmann检查c中嵌套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
            }
        }
    ]
}

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

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

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

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

原文由 S Andrew 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
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;
}

原文由 Niels Lohmann 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏