331

I've noticed the order of elements in a JSON object not being the original order.

What about the elements of JSON lists? Is their order maintained?

Machavity
  • 30,841
  • 27
  • 92
  • 100
user437899
  • 8,879
  • 13
  • 51
  • 71

5 Answers5

476

Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine):

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.

An array is an ordered sequence of zero or more values.

The terms "object" and "array" come from the conventions of JavaScript.

Some implementations do also preserve the order of JSON objects as well, but this is not guaranteed.

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Jeremy
  • 1
  • 85
  • 340
  • 366
  • 1
    However, I've spoken to some developers who have encountered problems where arrays are NOT ordered. Take a look at this oddly worded passage in http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf 'The JSON syntax does not define any specific meaning to the ordering of the values. However, the JSON array structure is often used in situations where there is some semantics to the ordering. ' – Cato Nov 04 '19 at 11:36
  • 3
    @Cato that passage does not mean that arrays may be unordered. It means that the reason for ordering an array may be unknown, because you do not specify why it is ordered. – Jose V Jul 03 '20 at 00:36
106

The order of elements in an array ([]) is maintained. The order of elements (name:value pairs) in an "object" ({}) is not, and it's usual for them to be "jumbled", if not by the JSON formatter/parser itself then by the language-specific objects (Dictionary, NSDictionary, Hashtable, etc) that are used as an internal representation.

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
  • Is this mentioned somewhere in "RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format" or where did you obtain this information? – hfrmobile Dec 07 '22 at 11:36
  • @hfrmobile - I learned it while developing the JSON package for the IBM I-Series computer line. – Hot Licks Dec 07 '22 at 13:20
12

Practically speaking, if the keys were of type NaN, the browser will not change the order.

The following script will output "One", "Two", "Three":

var foo={"3":"Three", "1":"One", "2":"Two"};
for(bar in foo) {
    alert(foo[bar]);
}

Whereas the following script will output "Three", "One", "Two":

var foo={"@3":"Three", "@1":"One", "@2":"Two"};
for(bar in foo) {
    alert(foo[bar]);
}
Salam Barbary
  • 301
  • 2
  • 2
  • 25
    But that's relying on undefined behavior on the part of JSON. Anything you interchange with may not have the same behavior. – Hot Licks Aug 27 '14 at 11:50
  • 8
    This answer discusses an object. The question relates to json "list", which can only be inferred to mean array, which is semantically ordered by json specification (see Jeremy's answer). – Tom Feb 14 '18 at 17:31
7

Some JavaScript engines keep keys in insertion order. V8, for instance, keeps all keys in insertion order except for keys that can be parsed as unsigned 32-bit integers.

This means that if you run either of the following:

var animals = {};
animals['dog'] = true;
animals['bear'] = true;
animals['monkey'] = true;
for (var animal in animals) {
  if (animals.hasOwnProperty(animal)) {
    $('<li>').text(animal).appendTo('#animals');
  }
}
var animals = JSON.parse('{ "dog": true, "bear": true, "monkey": true }');
for (var animal in animals) {
  $('<li>').text(animal).appendTo('#animals');
}

You'll consistently get dog, bear, and monkey in that order, on Chrome, which uses V8. Node.js also uses V8. This will hold true even if you have thousands of items. YMMV with other JavaScript engines.

Demo here and here.

Dave R.
  • 7,206
  • 3
  • 30
  • 52
Benjamin Atkin
  • 14,071
  • 7
  • 61
  • 60
  • 11
    But that's relying on undefined behavior on the part of JSON. Anything you interchange with may not have the same behavior. – Hot Licks Mar 22 '13 at 12:10
  • It may work for small objects. It's quite reasonable to have an object implementation that stores the first three key/value pairs in an array, and switches to a hash table when the fourth entry is added. Or when your endusers have one more item than you ever tested. – gnasher729 Jan 07 '22 at 12:31
  • That's an object, right? The question was about lists. – PePa Jul 15 '23 at 03:29
  • @PePa this is an old question. Don't do that, please. – Benjamin Atkin Jul 19 '23 at 18:32
  • @BenjaminAtkin This question still shows up in search results, this page is still accessible. Doesn't a wrong or unclear answer deserve to be corrected or clarified? This answer was not clear in that it talks about an object, while the question was about lists (arrays). Future viewers will benefit from any clarification when confusion still exists. – PePa Jul 27 '23 at 01:15
2

"Is the order of elements in a JSON list maintained?" is not a good question. You need to ask "Is the order of elements in a JSON list maintained when doing [...] ?" As Felix King pointed out, JSON is a textual data format. It doesn't mutate without a reason. Do not confuse a JSON string with a (JavaScript) object.

You're probably talking about operations like JSON.stringify(JSON.parse(...)). Now the answer is: It depends on the implementation. 99%* of JSON parsers do not maintain the order of objects, and do maintain the order of arrays, but you might as well use JSON to store something like

{
    "son": "David",
    "daughter": "Julia",
    "son": "Tom",
    "daughter": "Clara"
}

and use a parser that maintains order of objects.

*probably even more :)

user123444555621
  • 148,182
  • 27
  • 114
  • 126
  • 2
    Wrong, at least if you're talking about JSON parser usage. V8 maintains the order, and my guess is that it alone accounts for more than 1% of JSON parser usage. http://code.google.com/p/v8/issues/detail?id=164#c1 – Benjamin Atkin Jul 06 '12 at 06:43
  • 3
    @BenAtkin It's funny that your link points to the explanation on how V8 does **not** maintain the order. – user123444555621 Jul 06 '12 at 07:16
  • 2
    "The de facto standard is to match insertion order, which V8 also does, but with one exception" – Benjamin Atkin Jul 06 '12 at 16:48
  • 23
    All humans are male, but with one exception: Women are female. – user123444555621 Jul 06 '12 at 18:17
  • @user123444555621 :D The statement: "_All humans are male, but with one exception: Women are female_" covers all possible cases, but with one exception: humans that cannot be clearly classified as either can be classified eihter as both or as neither. – andowero Dec 14 '21 at 09:52