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

Initializing json by direct initialization and copy initialization invokes different constructors #4174

Closed
2 tasks done
FeignClaims opened this issue Oct 4, 2023 · 2 comments

Comments

@FeignClaims
Copy link

Description

  • direct initialization demo

    #include <iostream>
    #include <ostream>
    
    #include <nlohmann/json.hpp>
    
    auto main() -> int {
      std::map<std::string, std::string> map{{"key", "val"}, {"key2", "val2"}};
      nlohmann::json json{map};
      std::cout << json << '\n';  // output: [{"key":"val","key2":"val2"}]
      map = json;                 // exception: [json.exception.type_error.302] type must be object, but is array
    }
  • copy initialization demo

    #include <iostream>
    #include <ostream>
    
    #include <nlohmann/json.hpp>
    
    auto main() -> int {
      std::map<std::string, std::string> map{{"key", "val"}, {"key2", "val2"}};
      nlohmann::json json(map);
      std::cout << json << '\n';  // output: {"key":"val","key2":"val2"}
      map = json;                 // ok
    }

I think this behaviour is easy to make mistakes, so probably not an intentional design.

Reproduction steps

refer to description

Expected vs. actual results

The direct initialization code should behave as the same as the copy initialization one, which enables converting json back to std::map.

Minimal code example

No response

Error messages

No response

Compiler and operating system

x86-64 clang (trunk), x86-64 gcc (trunk)

Library version

35c0b3e

Validation

@gregmarr
Copy link
Contributor

gregmarr commented Oct 4, 2023

This is the very first item in the FAQ. https://json.nlohmann.me/home/faq/

@FeignClaims
Copy link
Author

I see, only searched in issue, sorry for the bother

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants