8

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.

Bennett
  • 1,007
  • 4
  • 15
  • 29

2 Answers2

11

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

philipp
  • 15,947
  • 15
  • 61
  • 106
  • 1
    This answer could be much stronger if it included some authoritative link to some spec like a IETF RFC that documents the order is guaranteed. Otherwise we just have to accept the author's belief it is true. [This answer does that](https://stackoverflow.com/a/7214312/190243) – Logachu Jan 17 '23 at 20:39
4

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.

slebetman
  • 109,858
  • 19
  • 140
  • 171
  • "lists are always ordered" no. – vstepaniuk Dec 08 '22 at 10:06
  • @vstepaniuk Linked lists are by definition ordered. You can reasonably ask what is the 3rd item in a list by looping through the next pointer 2 times. However you can't quite reasonably ask what is the 4th item in a set or a hash table without first specifying what you mean by 4th - insertion order? alphabetic order of the hash? numeric order of the hash? etc. Programming languages like Tcl and Lisp call what most other languages call "array" **lists** because of this. In those languages (and in computer science in general) arrays and lists are similar types of data structures. – slebetman Dec 08 '22 at 10:22