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

Incorrect convert map to json when key cannot construct an string i.e. int #2564

Closed
1 of 3 tasks
akeyliu opened this issue Jan 5, 2021 · 1 comment
Closed
1 of 3 tasks
Labels
solution: wontfix the issue will not be fixed (either it is impossible or deemed out of scope)

Comments

@akeyliu
Copy link

akeyliu commented Jan 5, 2021

What is the issue you have?

I'm now using nlohmann/json to convert my variables in C++. I find the conversion the map whose keys cannot construct an std::string to json is not run as expected. for example, the map with key is int type.

  1. It's very common that map's key is not string type, for example, serial number is integer.
  2. When map's key cannot construct an string, convert to json will output as sequnce container.
  3. My question is that if the map key value can try to convert to string (i.e. using to_string function) to before convert the map to json?

Please describe the steps to reproduce the issue.

Can you provide a small but working code example?

Example Code:
std::map<int, int> c_map_1 { {1, 101}, {2, 202}, {3, 303} };
json j_map_1(c_map_1);
std::map<std::string, int> c_map_2 { {"one", 1}, {"two", 2}, {"three", 3} };
json j_map_2(c_map_2);
std::map<int, std::string> c_map_3 { {1, "one"}, {2, "two"}, {3, "three"} };
json j_map_3(c_map_3);
cout << j_map_1 << endl << j_map_2 << endl << j_map_3 << endl;

Run Result:
[[1,101],[2,202],[3,303]]
{"one":1,"three":3,"two":2}
[[1,"one"],[2,"two"],[3,"three"]]

Expected Result:
{"1":101,"2":202,"3":303}
{"one":1,"three":3,"two":2}
{"1":"one","2":"two","3":"three"}

Which compiler and operating system are you using?

  • Compiler: ___g++ 9.3.0
  • Operating system: ___Ubuntu 20.04 LTS

Which version of the library did you use?

  • latest release version 3.9.1
  • other release - please state the version: ___3.7.3
  • the develop branch
@nlohmann
Copy link
Owner

nlohmann commented Jan 5, 2021

This is not a bug, but documented behavior. The library never performs implicit number-to-string conversion. If you want to have such behavior, you need to write your own converter function and not rely on the built-in conversions.

@nlohmann nlohmann added the solution: wontfix the issue will not be fixed (either it is impossible or deemed out of scope) label Jan 10, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
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