JSON convert Map with Integer keys JSON convert Map with Integer keys json json

JSON convert Map with Integer keys


Like @HotLicks said, when you convert objects to JSON, the key part of the JSON map will be returned as a String. I don't believe there's any way to move around this behavior. I'd also steer clear of using integers as keys in your map, if the intended behavior is as a JSON map. Instead, I'd do something like:

map.put("identifier", 1);map.put("value", "sample");

It's a little bit more verbose, but it's also easier to see how that translates to JSON.


It seems like map<int,int> is not matched properly. It is possible to use a derived class - like so:

struct Int_int_map : map<int, int> {    inline friend void to_json(json &j, Int_int_map const &m) {        j = json();        for (auto &key_val : m)            j[to_string(key_val.first)] = key_val.second;    }    inline friend void from_json(const json &j, Int_int_map &m) {        for (auto &key_val : j.get<json::object_t>())             m[std::stoi(key_val.first)] = key_val.second;           }};


The map can also be stored as an array of tuples/pairs.

{  "myMap" : [    {"key": 1, "value": 42},     {"key": 2, "value": 21},     {"key": 3, "value": 31415}  ]}