It's obvious that I can't rely on the ordering of key-value pairs in JSON. For example, a JSON parser could interpret
{
"someKey" : "someValue",
"anotherKey" : "anotherValue",
"evenAnotherKey" : "evenAnotherValue"
}
as
{
"anotherKey" : "anotherValue",
"someKey" : "someValue",
"evenAnotherKey" : "evenAnotherValue"
}
legally, but could I rely on the ordering of a JSON array? For example, could a JSON parser interpret
{
"arrayKey" : ["firstElement", "secondElement", "thirdElement"]
}
as
{
"arrayKey" : ["secondElement", "firstElement1", "thirdElement"]
}
legally? I'd assume not, but my friend told me that I was incorrect.
Yes, you can! Arrays are made, so that order matters! That is what divides Objects from Arrays. Especially in JS and JSON.
Arrays and lists are always ordered. That's the point of having arrays and lists - their position is their index.
Incidentally, since ES5 the order of objects (what you call key-value pairs) are guaranteed as well. But not in a straightforward way.
For objects, any key that is a number will be ordered before non-numeric keys and will be ordered numerically. But all other keys are guaranteed to be in insertion order. So the following object:
{
hello : "world",
foo : "bar",
"22" : "first"
}
must be returned as:
{
"22" : "first",
hello : "world",
foo : "bar"
}
Currently all browsers support this and node.js support this but not all javascript cross-complier (like Babel) support it.
Personally I don't like to treat unordered data structures like objects as ordered. But it looks like the js community disagrees. Go for example deliberately randomises the ordering of maps to prevent people from relying on any accidental stable ordering from an implementation of the language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With