Skip to content

pass a json object to a class contructor adds an array around the object #1776

@strahlc

Description

@strahlc

When I pass a json object to a class contructor, an array is added around my object

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


class A {
	public:
		A(const nlohmann::json &by_ref) : _by_ref{by_ref} {
			std::cout << _by_ref.dump(4) << "\n\n";
		}
	private:
		nlohmann::json _by_ref{};
};


class B {
	public:
		B(nlohmann::json by_val) : _by_val{std::move(by_val)} {
			std::cout << _by_val.dump(4) << "\n\n";
		}
	private:
		nlohmann::json _by_val{};
};


int main() {
	nlohmann::json json_object;
	json_object["key1"] = "val1";

	std::cout << json_object.dump(4) << "\n\n";

	A a{json_object};
	B b{json_object};

	return EXIT_SUCCESS;
}

Output

{
    "key1": "val1"
}

[
    {
        "key1": "val1"
    }
]

[
    {
        "key1": "val1"
    }
]

I would expect all three outputs like the first one.

I'm using gcc-8.3.0 on gentoo linux and nlohmann_json-3.7.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind: bugsolution: proposed fixa fix for the issue has been proposed and waits for confirmation

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions