3 ms·
It is a stable sort since for almost every parser out there there can be no duplicate keys. It would be dangerous for an JSON parser to assume JSON object keys
by peterohler 6y ago
It is a stable sort since for almost every parser out there there can be no duplicate keys. It would be dangerous for an JSON parser to assume JSON object keys are in some specific order. It is certainly not something that can be counted on in golang, Ruby, or Python.
- Splognosticus 6y agoAlso in violation of the spec: > An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array. https://tools.ietf.org/html/rfc7159#section-1 https://tools.ietf.org/html/rfc7159#section-1
- taeric 6y agoThe spec does call out that some parsers deal with this. And since it is javascript based, leniency is the norm. That is, you could rely on this and but be aware of it, is my point. Firefox, for example, will happily take an object with duplicates and report only the last one.
- Splognosticus 6y agoWell, by definition "unordered" means you can't count on any particular order. So while parsers may indeed preserve order, anything that relies on it is in violation of the standard. That said, I agree that being aware of this is important if you're emitting JSON. You'd think nobody would ever address a JSON object by its ordinal position, but programmers are lazy and worse, think they're clever. :)
- taeric 6y agoExactly that. I did not mean to disagree that it is somewhat wrong. Just feels dangerous, as behavior could change with no side channel warnings.
- quietbritishjim 6y ago> It is certainly not something that can be counted on in golang, Ruby, or Python. As of Python 3.6 (in theory not guaranteed until Python 3.7), key order is preserved when reading and writing. That's a consequence of the fact Python dictionaries can now remember the order of insertion. It's true that it doesn't support duplicate keys though (unless you pass in a different class to the object_pairs_hook parameter of loads() to replace its use of dict).