Json: Assertion failed on ["NoExistKey"] of an not existing key of const json&

Created on 8 Nov 2017  路  3Comments  路  Source: nlohmann/json

Bug Report

  • What is the issue you have?
    If you try to assign a key (that dosnt exist) from a const json& to const json& or json an assert is fire :
    "Assertion `m_value.object->find(key) != m_value.object->end()' failed"

  • Please describe the steps to reproduce the issue. Can you provide a small but working code example?

``

#include <iostream>
#include <string>
#include <sstream>
#include <json.hpp>

using json = nlohmann::json;

int main(){

json dummy = R"({
  "OggetoUno": {
    "Numero": 1510161606
  },
  "OggettoDue": {
  }
})"_json;

const json& dummyRef = dummy;

const json& a = dummyRef["OggetoUno"]["Numero"];
std::cout << std::setw(4) << a.is_null() << '\n';
std::cout << std::setw(4) << a.empty() << '\n';

const json& b = dummyRef["OggettoDue"]["Numero"];
std::cout << std::setw(4) << b.is_null() << '\n';
std::cout << std::setw(4) << b.empty() << '\n';

return 99;
}

``

  • What is the expected behavior?
    If 'b' is const json& a reference to.
    If 'b' is json a copy of x, in that case a null json.
  • And what is the actual behavior instead?
    "Assertion `m_value.object->find(key) != m_value.object->end()' failed"

  • Which compiler and operating system are you using? Is it a supported compiler?

  • VS2015 on W10
  • https://wandbox.org/

Best regards
Paolo

All 3 comments

This is the expected behavior. See the first note in the README.

The code contains numerous debug assertions which can be switched off by defining the preprocessor macro NDEBUG, see the documentation of assert. In particular, note operator[] implements unchecked access for const objects: If the given key is not present, the behavior is undefined (think of a dereferenced null pointer) and yields an assertion failure if assertions are switched on. If you are not sure whether an element in an object exists, use checked access with the at() function.

Thank you I will change my code,
but for future features may be useful that [] operator (that is very readable code) can be return null json object.
Sometime when the key doesnt exist it's useful have a default value and dont use find then read and so on or catch exception.
i.e.

json a ... read from file
readObj(a);
....

void readObj (const json& r2a)
{
json obj1 = r2a["level1"]["level2"]["level3"];
if (obj1.is_null()) { ... } else { ... }
}

Dont you ?

For this, we have the value function. Also, checking for keys can be done with find.

Was this page helpful?
0 / 5 - 0 ratings