Repository navigation
Automatic ordered JSON #424
Description
Activity
https://github.com/nlohmann/json/blob/master/.github/CONTRIBUTING.md
We do not preserve the insertion order of object elements. The JSON standard defines objects as "an unordered collection of zero or more name/value pairs". To this end, this library does not preserve insertion order of name/value pairs. (In fact, keys will be traversed in alphabetical order as std::map with std::less is used by default.) Note this behavior conforms to the standard, and we shall not it to any other order.
You can check out https://github.com/nlohmann/fifo_map - it should work as a replacement of std::map and maintains the key's order.
Reacted by Mickaël Bettinelli and menkaur- addedsolution: duplicatethe issue is a duplicate; refer to the linked issue insteadthe issue is a duplicate; refer to the linked issue instead
on Jan 9, 2017 Hi. A quick question regarding this issue (just out of curious): why not use std::unordered_map by default instead of std::map? After all, json objects are unsorted by semantics. And unordered_map should gain significant speed up regarding the time complexity.
Reacted by menkaurThe problem is that we are defining an object
basic_jsonand inside a member of typestd::map<std::string, basic_json>. At this point,basic_jsonis not yet fully defined. This seems to be OK forstd::mapon all platforms/compilers I encountered so far, but it is not forstd::unordered_map.Hi, is there any way to sort nlohmann::json depending upon values, like for example,
if key is string and value is double, can I sort json based on double?Can you give an example for this?
Example:
if input = {
"abc" : 0.288,
"pqr" : 0.176,
"xyz" : 0.555,
"zaz" : 0.345
}
After sorting it should look something like,
output = {
"pqr" : 0.176,
"abc" : 0.288,
"lmo" : 0.345,
"xyz" : 0.555
}
Basically sorted by values.This is not possible in the library (see https://github.com/nlohmann/json#order-of-object-keys). You could parse the value into some C++ container (e.g., a vector of pairs) and sort it yourself.
Thanks for the support.
Hey, is there a way to use std::max_element with nlohmann::json to get the key-value pair with the highest value for the above-given example?
prototype:
auto max = std::max_element (j.begin(), j.end(), cmp);You may be able to achieve this via the
items()function.To be fixed with #2258.
- addedsolution: proposed fixa fix for the issue has been proposed and waits for confirmationa fix for the issue has been proposed and waits for confirmation
on Jul 11, 2020
Hi,
Json is automatically sorted by an alphabetic order. I don't find any information about that in your readme. Is there a way to avoid sorting ?