Json: Automatic ordered JSON

Created on 9 Jan 2017  路  12Comments  路  Source: nlohmann/json

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 ?

question release item new feature duplicate proposed fix

Most helpful comment

https://github.com/nlohmann/json/issues/106

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.

All 12 comments

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.

https://github.com/nlohmann/json/issues/106

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.

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.

The problem is that we are defining an object basic_json and inside a member of type std::map<std::string, basic_json>. At this point, basic_json is not yet fully defined. This seems to be OK for std::map on all platforms/compilers I encountered so far, but it is not for std::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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zkelo picture zkelo  路  3Comments

qis picture qis  路  4Comments

afowles picture afowles  路  3Comments

dcube9 picture dcube9  路  3Comments

mlund picture mlund  路  4Comments