Skip to content

basic_json::contains

template<typename KeyT>
bool contains(KeyT && key) const;

Check whether an element exists in a JSON object with key equivalent to key. If the element is not found or the JSON value is not an object, false is returned.

Template parameters

KeyT
A type for an object key other than basic_json::json_pointer.

Parameters

key (in)
key value to check its existence.

Return value

true if an element with specified key exists. If no such element with such key is found or the JSON value is not an object, false is returned.

Exception safety

Strong exception safety: if an exception occurs, the original value stays intact.

Complexity

Logarithmic in the size of the JSON object.

Notes

This method always returns false when executed on a JSON type that is not an object.

Example

Example

The example shows how contains() is used.

#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main()
{
    // create some JSON values
    json j_object = R"( {"key": "value"} )"_json;
    json j_array = R"( [1, 2, 3] )"_json;

    // call contains
    std::cout << std::boolalpha <<
              "j_object contains 'key': " << j_object.contains("key") << '\n' <<
              "j_object contains 'another': " << j_object.contains("another") << '\n' <<
              "j_array contains 'key': " << j_array.contains("key") << std::endl;
}

Output:

j_object contains 'key': true
j_object contains 'another': false
j_array contains 'key': false

Version history

  • Added in version 3.6.0.