13

For example, with nlohmann::json, I can do

map<string, vector<int>> m = { {"a", {1, 2}}, {"b", {2, 3}} };
json j = m;

But I cannot do

m = j;

Any way to convert a json object to a map with nlohmann::json?

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
user1899020
  • 13,167
  • 21
  • 79
  • 154
  • I recommend you upvote and accept @Fred's answer below. (If you don't maintain your questions, you'll get downvoted!) – P i Apr 15 '19 at 13:41

4 Answers4

15

nlomann::json can convert Json objects to most standard STL containers with get<typename BasicJsonType>() const

Example:

// Raw string to json type
auto j = R"(
{
  "foo" :
  {
    "bar" : 1,
    "baz" : 2
  }
}
)"_json;

// find object and convert to map
std::map<std::string, int> m = j.at("foo").get<std::map<std::string, int>>();
std::cout << m.at("baz") << "\n";
// 2
Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
Fred
  • 417
  • 6
  • 14
4

There is function get in class json.

Try something along these lines:

m = j.get<std::map <std::string, std::vector <int>>();

You might have to fiddle a bit with it to make it work precisely the way you want it to.

Lehu
  • 761
  • 4
  • 14
2

The only solution that I found is just to parse it manually.

    std::map<std::string, std::vector<int>> m = { {"a", {1, 2}}, {"b", {2, 3}} };
    json j = m;
    std::cout << j << std::endl;

    auto v8 = j.get<std::map<std::string, json>>();

    std::map<std::string, std::vector<int>> m_new;
    for (auto &i : v8)
    {
        m_new[i.first] = i.second.get<std::vector<int>>();
    }


    for(auto &item : m_new){
        std::cout << item.first << ": " ;
        for(auto & k: item.second ){
            std::cout << k << ",";
        }
        std::cout << std::endl;
    }

If there is a better way I would appreciate a hint.

LennyLinux
  • 93
  • 11
0

In fact, your code is perfectly valid with the current version (2.0.9).

I tried:

std::map<std::string, std::vector<int>> m = { {"a", {1, 2}}, {"b", {2, 3}} };
json j = m;
std::cout << j << std::endl;

and got the output

{"a":[1,2],"b":[2,3]}
Niels Lohmann
  • 2,054
  • 1
  • 24
  • 49