Checking if a key exists in JSON

What is the best way to check if a specific key exists in a JSON object?

There are a couple of ways to check if a key exists in a JSON object.

One option is to use the contains() method:

#include <iostream>
#include <json.hpp>
using json = nlohmann::json;

int main() {
  using namespace nlohmann::literals;
  json doc{R"(
    {
      "name": "Roderick",
      "health": 100
    }
  )"_json};

  if (doc.contains("name")) {
    std::cout << "JSON object contains 'name'";
  }
}
JSON object contains 'name'

contains() will return true if the key exists in the object, even if the corresponding value is null.

Another option is to use find():

#include <iostream>
#include <json.hpp>
using json = nlohmann::json;

int main() {
  using namespace nlohmann::literals;
  json doc{R"(
    {
      "name": "Roderick",
      "health": 100
    }
  )"_json};

  auto it = doc.find("health");
  if (it != doc.end()) {
    std::cout << "JSON object contains 'health'";
  }
}
JSON object contains 'health'

find() returns an iterator to the key/value pair if the key exists. We can compare this iterator to end() to determine if the key was found or not.

A third way is to use the [] operator and check if the result is a null json value:

#include <iostream>
#include <json.hpp>
using json = nlohmann::json;

int main() {
  using namespace nlohmann::literals;
  json doc{R"(
    {
      "name": "Roderick",
      "health": 100
    }
  )"_json};

  if (doc["mana"].is_null()) {
    std::cout << "JSON object contains does"
      " not contain 'mana' key";
  }
}
JSON object contains does not contain 'mana' key

However, this will actually add the key to the object if it doesn't already exist, so it's not always ideal.

In general, contains() is the most straightforward way to test for a key's existence in a JSON object.

Using JSON in Modern C++

A practical guide to working with the JSON data format in C++ using the popular nlohmann::json library.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Creating a JSON object from a file
How can I create a JSON object by reading the contents of a JSON file?
Pretty-printing JSON
How can I print out JSON in a nicely formatted way?
Serializing private class members to JSON
How can I serialize private members of a class to JSON?
Using custom types as JSON keys
Can I use a custom type as a key in a JSON object?
Adding comments to JSON
Can I add comments to a JSON file to document what certain parts mean?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant