Using JSON in Modern C++

Checking if a key exists in JSON

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

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved