gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
nlohmann 键 值为null导致取值崩溃
- User
nlohmann 键 值为null导致取值崩溃
- Assistant
对于nlohmann库中的Json对象,如果键对应的值为null,则取值操作会导致崩溃。因为nlohmann库默认情况下不允许查找null值的成员。
为了避免这种情况,你可以使用
at()成员函数来代替[]操作符来获取键对应的值。at()函数会抛出一个异常std::out_of_range,如果键不存在或者对应的值为null。下面是一个示例:
#include <nlohmann/json.hpp> #include <iostream> using json = nlohmann::json; int main() { json data = R"( { "key": null } )"_json; try { auto value = data.at("key"); // 使用at()函数获取键对应的值 if (value.is_null()) { std::cout << "value is null" << std::endl; } else { std::cout << "value is not null" << std::endl; } } catch (const std::exception& e) { std::cout << "key not found" << std::endl; } return 0; }在此示例中,如果键"key"对应的值为null,将会输出"value is null"。否则,如果键不存在,则会输出"key not found"。