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

Conversion error for std::map<int, std::string> #739

Closed
MariaRamos89 opened this issue Sep 13, 2017 · 4 comments
Closed

Conversion error for std::map<int, std::string> #739

MariaRamos89 opened this issue Sep 13, 2017 · 4 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@MariaRamos89
Copy link

MariaRamos89 commented Sep 13, 2017

Hi,

I'm trying to save a std::map<int, std::string> 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

@nlohmann
Copy link
Owner

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;
}

@nlohmann nlohmann added kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation labels Sep 13, 2017
@MariaRamos89
Copy link
Author

Thanks,
Now it's working :)

@lattice0
Copy link

I'm actually ok with [ [1, "one"], [2, "two"]] but I cant make it work: #2378. Any ideas on why?

@nlohmann
Copy link
Owner

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"]]

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

3 participants