arduino-libraries / Arduino_JSON

Official JSON Library for Arduino
GNU Lesser General Public License v2.1
154 stars 60 forks source link

Convert std::map and std::unordered_map to JSON object #45

Open Zhu-jiatong opened 1 year ago

Zhu-jiatong commented 1 year ago

While developing a webserver, I discovered that JSON and maps have a lot in common. To be more specific, a key-value pair, where the key is used to retrieve the corresponding value. In addition, it is syntactically similar as well, e.g.,

// map
std::unordered_map<String, String> my_map;
my_map["first element"] = "text string";

// JSON
JSONVar my_JSON;
my_JSON["key"] = "value";

Please consider adding a feature to convert a std::map/unordered_map to a JSONVar. This feature could be used in many cases, e.g., serialise user information, file information and device information to be stored in a file or sent across the Internet. Thank you.

Zhu-jiatong commented 1 year ago

It is important to acknowledge that not all datatypes are supported. For example, std::unordered_map<String, struct> is rather difficult to be converted to JSON object. For multidimensional maps of supported types, the library could convert it into a multi-level JSON, i.e., std::unordered_map<String, std::unordered_map<String, int>> ==> JSONVar["xxx"][n].

Zhu-jiatong commented 1 year ago

I would propose something like this:

std::unordered_map<String, int> my_umap; // create an unordered_map
JSONVar my_JSON_obj; // create instance of JSONVar
my_JSON_obj = JSON.parse(my_umap); // parse unordered_map to JSON object
JSON.stringify(my_JSON_obj); // output JSON string

As for the implementation part, it could be done by recursively traversing the map until all layers are accessed. It may also be done iteratively if possible.