Json: Conversion error for std::map<int, std::string>

Created on 13 Sep 2017  Â·  4Comments  Â·  Source: nlohmann/json

Hi,

I'm trying to save a std::map into a json, and then the json is saved in a file.

nlohmann::json db;
db = mymap;
std::ofstream output_file(filename);
output_file << std::setw(4) << db << std::endl;

The problem is the result of the json:

I'm expecting this kind of output:
{ 1 : "one", 2 : "two"}
However, the result is:
[ [1, "one"], [2, "two"]]

So, when in other program I'm trying to read that file and try to save it in a json for doing the conversion to std::map again, I'm having the next error:

error: ambiguous overload for ‘operator=’ (operand types are ‘std::map<int, std::__cxx11::basic_string<char> >’ and ‘nlohmann::json {aka nlohmann::basic_json<>}’)

I've been looking in similar errors like #607, but I don't find a solution.
I've tried to build the map manually but the output is the same. Maybe I'm missing something.

Thanks in advance

question proposed fix

Most helpful comment

Keys of JSON objects must be strings:

The library does not convert the keys of the std::map to strings automatically, and under the hood a list of pairs is the closest we can get inside JSON. You need to make the conversion yourself, e.g. with code like

for (auto it = mymap.begin(); it != mymap.end(); ++it)
{
  db[std::to_string(it->first)] = it->second;
}

All 4 comments

Keys of JSON objects must be strings:

The library does not convert the keys of the std::map to strings automatically, and under the hood a list of pairs is the closest we can get inside JSON. You need to make the conversion yourself, e.g. with code like

for (auto it = mymap.begin(); it != mymap.end(); ++it)
{
  db[std::to_string(it->first)] = it->second;
}

Thanks,
Now it's working :)

I'm actually ok with [ [1, "one"], [2, "two"]] but I cant make it work: https://github.com/nlohmann/json/discussions/2378. Any ideas on why?

Nothing broken here:

    std::map<int, std::string> m;
    m[1] = "one";
    m[2] = "two";
    std::cout << json(m) << std::endl;

Output:

[[1,"one"],[2,"two"]]
Was this page helpful?
0 / 5 - 0 ratings