nlohmann / json

JSON for Modern C++
https://json.nlohmann.me
MIT License
41.3k stars 6.58k forks source link

JSON parses as array when assigned in initializer list. #4278

Closed YourAverageFTCPerson closed 5 months ago

YourAverageFTCPerson commented 5 months ago

Description

I don't know if this is intended or not (although it seems very unlikely that it is), but when I make a class with a member json variable and assign it in the initializer list (with a parameter from the constructor), it always wraps the json in an extra array of length one. (This doesn't happen when you just assign the member variable to the constructor parameter without the initializer list.)

Reproduction steps

Make a class with a json member variable and a constructor with a json parameter intended to be the value of the member variable. Assign the member variable as the parameter in the initializer list of the constructor. It's the same json object, just in a json array of length one.

Expected vs. actual results

It should just be a json object, but for some reason it's a single element json array containing the object.

Minimal code example

#include <cassert>

#include <json/json.hpp>

#include <iostream>

using json = nlohmann::json;

class Test1
{
public:
    json j;
    Test1(json j) : j{ j }
    {
    }
};

class Test2
{
public:
    json j;
    Test2(json j)
    {
        this->j = j;
    }
};

int main()
{
    std::cout << Test1{ R"""(
        {"foo": "bar"}
        )"""_json }.j.type_name() << std::endl; // Prints array
    assert(Test1{ R"""(
        {"foo": "bar"}
        )"""_json }.j.type() == json::value_t::array); // No errors
    assert(Test2{ R"""(
        {"foo": "bar"}
        )"""_json }.j.type() == json::value_t::object); // No errors

    return 0;
}

Error messages

No response

Compiler and operating system

Windows 10, MSVC Community 2022 C++ 20

Library version

3.11.3

Validation

nlohmann commented 5 months ago

See https://json.nlohmann.me/home/faq/#brace-initialization-yields-arrays and #2583