Search code examples
linuxc++14nullptrnlohmann-json

nlohmann json has a string member called name, how can I check it is null or valid string


I know that I have this:

json var["thirdName"].get<std::string>().c_str();

It is used in C++. The protocol says this member is mandatory, but lots of people don't have third name.

I got exception if it is

nullptr;

, because I can say

var["thirdName"] = nullptr;

How can I easily check if it is valid or not?

I've found only one very complex form.


Solution

  • You can use the count method:

    if (var.count("thirdName") > 0) {
      ...
    }
    

    Personally, I would omit the > 0:

    if (var.count("thirdName")) {
      ...
    }