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

While trying to make a simple array, I get a nested array instead #1848

Closed
jlconlin opened this issue Nov 20, 2019 · 3 comments
Closed

While trying to make a simple array, I get a nested array instead #1848

jlconlin opened this issue Nov 20, 2019 · 3 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@jlconlin
Copy link

  • Describe what you want to achieve.
    I'm trying to make a simple JSON array for my custom class

  • Describe what you tried.

struct A{
  int c1;
  int c2;
};

void to_json( json& JSON, const A& a ){
  JSON = { A.c1, A.c2 };
}

A myA{ 21, 22};

auto json = nlohmann::json{ myA };
// Gives me [[ 21, 22]]
// Would like it to return [21, 22]

I've also tried (from #1013)

void to_json( json& JSON, const A& a ){
  JSON = std::forward_list< int >{ A.c1, A.c2 };
}

and got the same response.

  • Describe which system (OS, compiler) you are using.
    MacOS 10.14, LLVM 3.8

  • Describe which version of the library you are using (release version, develop branch).
    master branch, commit c0d511ea500e698061a4b288bd77ce43bd76fa70 (okay, it's kind of old)

@nlohmann
Copy link
Owner

The library interprets the braces in

auto json = nlohmann::json{ myA };

as array. Try replacing this by

nlohmann::json json = myA;

@nlohmann nlohmann added the solution: proposed fix a fix for the issue has been proposed and waits for confirmation label Nov 21, 2019
@jlconlin
Copy link
Author

This works, but I'm struggling to understand the difference. Why aren't the braces interpreted as brace initialization?

@nlohmann
Copy link
Owner

I think it is interpreted as an initializer list, and the corresponding (implicit) constructor creates an array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

2 participants