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

Can not translate map with integer key to dict string ? #1664

Closed
ruoshui1314 opened this issue Jul 9, 2019 · 6 comments
Closed

Can not translate map with integer key to dict string ? #1664

ruoshui1314 opened this issue Jul 9, 2019 · 6 comments
Labels
kind: bug solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@ruoshui1314
Copy link

ruoshui1314 commented Jul 9, 2019

It is correct to translate to dict string when the key of map is string.
But translate to an array when it is an integer.
` std::map<int, int> c_map;

c_map[1111] = 1;

c_map[2333] = 111;

nlohmann::json j_map = c_map;

std::cout << j_map.dump() << std::endl;

`
result:

[[1111,1],[2333,111]]

How could I solve it?

@nlohmann
Copy link
Owner

nlohmann commented Jul 9, 2019

To create a JSON object, the keys must be strings; this is required by the JSON specification.

All other mappings are translated into a list of key/value pairs.

@nlohmann nlohmann added the solution: proposed fix a fix for the issue has been proposed and waits for confirmation label Jul 9, 2019
@ruoshui1314
Copy link
Author

Got it

@bradallred
Copy link

I understand the JSON requirement that keys must be strings. My question is then, what is the most convenient way to translate an unordered_map with integer keys into a JSON object with keys that are the string representation of the integers? Must we write a custom to_json function for the map, or is there something I have overlooked that will pass map keys though std::to_string()?

@jaredgrubb
Copy link
Contributor

That sounds like the right approach to me!

@bradallred
Copy link

Indeed this seems to work! :)

here is what I did for any future travelers that need the same:

void to_json(nlohmann::json& j, const Map& map)
{
	for (auto& [key, value] : map) {
		j.push_back({{std::to_string(key), value}});
	}
}

@bear24rw
Copy link

Is there any better way to do this nowadays? I had to make a new map type because I couldn't get from_json to override the default behavior. It is undesirable to have to introduce a new type just for json serialization reasons.

class UnorderedMap : public std::unordered_map<int, double> {};

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

No branches or pull requests

5 participants