Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
strahlc opened this issue Oct 4, 2019 · 3 comments
Closed
Labels
kind: bug solution: wontfix the issue will not be fixed (either it is impossible or deemed out of scope)

Comments

@strahlc
Copy link

strahlc commented Oct 4, 2019

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

@nlohmann
Copy link
Owner

nlohmann commented Oct 5, 2019

Braces are treated like arrays to allow this syntax:

json x = {1,2,3,4}; // [1,2,3,4]

Therefore, {json_object} will be treated as an array containing whatever is in json_object.

@strahlc
Copy link
Author

strahlc commented Oct 5, 2019

In our project we have to follow the cpp coreguidelines, including ES.23: Prefer the {}-initializer syntax [1].
From that perspective that is an extremely unexpected behavior, because the standard says ={} gives copy initialization whereas {} gives direct initialization.

Would it be possible to restrict this behavior to copy initialization?

[1] http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es23-prefer-the--initializer-syntax

@nlohmann
Copy link
Owner

nlohmann commented Oct 5, 2019

I'm afraid this behavior cannot be changed without breaking existing code.

@nlohmann nlohmann added the solution: wontfix the issue will not be fixed (either it is impossible or deemed out of scope) label Oct 5, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: bug solution: wontfix the issue will not be fixed (either it is impossible or deemed out of scope)
Projects
None yet
Development

No branches or pull requests

2 participants