3 ms·
Yes, but it's not impossible to achieve it in practice. For example, JavaScript JSON.stringify and JSON.parse have well-defined behaviour: > Properties are vi
by ash 3y ago
Yes, but it's not impossible to achieve it in practice.
For example, JavaScript JSON.stringify and JSON.parse have well-defined behaviour:
> Properties are visited using the same algorithm as Object.keys(), which has a well-defined order and is stable across implementations
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
> The traversal order, as of modern ECMAScript specification, is well-defined and consistent across implementations. Within each component of the prototype chain, all non-negative integer keys (those that can be array indices) will be traversed first in ascending order by value, then other string keys in ascending chronological order of property creation.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
Similarly, Python json module guarantees that "encoders and decoders preserve input and output order by default. Order is only lost if the underlying containers are unordered." Since 3.7 dict maintains insertion order.
https://docs.python.org/3/library/json.html https://docs.python.org/3/library/json.html
https://docs.python.org/3/library/stdtypes.html#dict https://docs.python.org/3/library/stdtypes.html#dict
Yes, JS and Python behaviour are not the same for all cases, however, non-integer keys do maintain order across Python and JavaScript.
- cryptonector 3y ago> Yes, but it's not impossible to achieve it in practice. For any one implementation. But there's a very large number of implementations. You just can't count on object key order being preserved, so don't.
- ash 3y agoThere are situations where keeping order is useful. For example, human-editable json config files. I also gave an example of two implementations that are compatible for a useful subset of keys. By the way, SQLite JSONB keeps object keys in insertion order, similar to Python: https://news.ycombinator.com/item?id=38547254 https://news.ycombinator.com/item?id=38547254
- cryptonector 3y ago> There are situations where keeping order is useful. For example, human-editable json config files. You might have to just normalize every time you want to edit that.
- anamexis 3y agoYou can count on object key order being preserved when you control the implementation. Which is why it's useful to know whether a given implementation preserves key order.