Files
json/docs/mkdocs/docs/api/basic_json/std_hash.md
T
Afonso Januário c66be708eb Make std::hash<basic_json> consistent with operator== for numbers
operator== converts between number_integer, number_unsigned, and
number_float before comparing, so json(0), json(0U), and json(0.0)
all compare equal. hash() folded the specific value_t into the
result for each of the three numeric cases, giving each a distinct
hash and breaking the standard Hash requirement that a == b implies
hash(a) == hash(b). A std::unordered_set could therefore hold all
three as separate elements even though they compare equal.

hash() now treats all three numeric variants the same way: it
converts the value to number_float_t and combines it with a single
shared type tag, so any two numbers operator== considers equal hash
identically regardless of which internal type actually holds them.

Updated the accompanying test to check this consistency directly
(including via an actual unordered_set) instead of asserting that 0,
0U, and 0.0 hash differently, since that assumption was the bug.
Also corrected the function's own doc comment and the std::hash API
docs, which described the old behavior as intended.

Fixes #5400

Signed-off-by: Afonso Januário <afonso-januario@hotmail.com>
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-07 16:40:08 +02:00

1.0 KiB

std::hashnlohmann::basic_json\

namespace std {
    struct hash<nlohmann::basic_json>;
}

Return a hash value for a JSON object. The hash function tries to rely on std::hash where possible. Furthermore, the type of the JSON value is taken into account, so #!json null, #!cpp false, and numbers all hash differently from each other. Numbers that compare equal under operator== always hash equally, regardless of whether they are stored as #!cpp 0, #!cpp 0U, or #!cpp 0.0.

Examples

??? example

The example shows how to calculate hash values for different JSON values.
 
```cpp
--8<-- "examples/std_hash.cpp"
```

Output:

```json
--8<-- "examples/std_hash.output"
```

Note the output is platform-dependent.

See also

  • operator== compares two JSON values for equality, consistent with equal hash values

Version history

  • Added in version 1.0.0.
  • Extended for arbitrary basic_json types in version 3.10.5.