nlohmann/json

[bug] nlohmann::json constructor behaves improperly

Closed this issue · 1 comments

Description

"Direct initialization with an rvalue works fine, but adding another constructor causes all key-value pairs to be represented as a single value with the key '0'. This may cause problems in template programming.

Reproduction steps

compile the code snipper, then execute it.

Expected vs. actual results

direct version
id : "a"
message : "a"
rec : "b"
addition constructor version
0 : {"id":"a","message":"a","rec":"b"}

"Direct initialization with an rvalue works fine, but adding another constructor causes all key-value pairs to be represented as a single value with the key '0'. This may cause problems in template programming.

Minimal code example

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

using json = nlohmann::json;

void dump(const json& data) {
  for (auto& [key, value] : data.items()) {
    std::cout << key << " : " << value << "\n";
  }
}

int main() {
  // Malformed JSON data as a std::string
  std::string json_string = R"({"id": "a" , "rec" : "b" , "message" : "a"})";
  auto g = [&] { return nlohmann::json::parse(json_string); };
  std::cout << "direct version\n";

  auto g3 = g();
  dump(g3);

  std::cout << "addition constructor version\n";

  auto g4 = json{g()};
  dump(g4);

  return 0;
}

Error messages

No response

Compiler and operating system

gcc (Debian 12.2.0-14) 12.2.0 on Debian 12 using conan + cmake

Library version

nlohmann_json/3.11.3

Validation

The issue is line

auto g4 = json{g()};

The curly braces create an array (see https://json.nlohmann.me/home/faq/#brace-initialization-yields-arrays), so g4 has the value

[{"id":"a","message":"a","rec":"b"}]

When you then call items() on this, the "key" for this, it prints the first value of the array

{"id":"a","message":"a","rec":"b"}

together with the index 0.