Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I Rely on the Order of a JSON Array? [duplicate]

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.

like image 372
Bennett Avatar asked Jan 22 '17 17:01

Bennett


2 Answers

Yes, you can! Arrays are made, so that order matters! That is what divides Objects from Arrays. Especially in JS and JSON.

like image 181
philipp Avatar answered Sep 25 '22 11:09

philipp


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.

like image 42
slebetman Avatar answered Sep 23 '22 11:09

slebetman