Skip to content

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

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

Open
Zhu-jiatong opened this issue Dec 4, 2022 · 2 comments
Open

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

Zhu-jiatong opened this issue Dec 4, 2022 · 2 comments
Labels
topic: code Related to content of the project itself type: enhancement Proposed improvement

Comments

@Zhu-jiatong
Copy link

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.

@per1234 per1234 added type: enhancement Proposed improvement topic: code Related to content of the project itself labels Dec 5, 2022
@Zhu-jiatong
Copy link
Author

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
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic: code Related to content of the project itself type: enhancement Proposed improvement
Projects
None yet
Development

No branches or pull requests

2 participants