357

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?

0

6 Answers 6

508

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 object properties (name/value pairs) as well, but this is not guaranteed.

2
  • 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 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
    Commented Nov 4, 2019 at 11:36
  • 7
    @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
    Commented Jul 3, 2020 at 0:36
119

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.

2
  • Is this mentioned somewhere in "RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format" or where did you obtain this information?
    – hfrmobile
    Commented Dec 7, 2022 at 11:36
  • 2
    @hfrmobile - I learned it while developing the JSON package for the IBM I-Series computer line.
    – Hot Licks
    Commented Dec 7, 2022 at 13:20
14

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]);
}
2
  • 29
    But that's relying on undefined behavior on the part of JSON. Anything you interchange with may not have the same behavior.
    – Hot Licks
    Commented Aug 27, 2014 at 11:50
  • 10
    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
    Commented Feb 14, 2018 at 17:31
10

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.

4
  • 14
    But that's relying on undefined behavior on the part of JSON. Anything you interchange with may not have the same behavior.
    – Hot Licks
    Commented Mar 22, 2013 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
    Commented Jan 7, 2022 at 12:31
  • That's an object, right? The question was about lists.
    – PePa
    Commented Jul 15, 2023 at 3:29
  • 3
    @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
    Commented Jul 27, 2023 at 1: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 :)

4
  • 3
    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. code.google.com/p/v8/issues/detail?id=164#c1 Commented Jul 6, 2012 at 6:43
  • 3
    @BenAtkin It's funny that your link points to the explanation on how V8 does not maintain the order. Commented Jul 6, 2012 at 7:16
  • 2
    "The de facto standard is to match insertion order, which V8 also does, but with one exception" Commented Jul 6, 2012 at 16:48
  • @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
    Commented Dec 14, 2021 at 9:52
0

JSON objects are, by definition, unordered collections of key-value pairs, so any parser is free to rearrange those pairs when the data is read or later re-stringified. The apparent stability you sometimes see in JavaScript is only an implementation detail, not a guarantee of the JSON spec.

 let data = 
    { 
      id_1 : 
       {  
        aggregate: undefined, 
        alias: undefined, 
        tablename: "",
        columnname: "",

      },
     id_2 : 
      {
        aggregate: X, 
        alias: Y, 
        tablename: "",
        columnname: "",

      }
}

If you need to preserve sequence—say you have several IDs that must stay in the exact order they were inserted—use a JSON array instead, because arrays are intrinsically ordered and every compliant parser must keep that order intact. In practice, many applications combine the two ideas: they store the records in an array to maintain order for persistence or transmission, while also holding a separate in-memory map (e.g., a Map or plain object keyed by the same Ids) to get O(1) lookups during program execution.

let data = 
[
   {
     id: id_1,
     aggregate: undefined,
     alias: undefined,
     tablename: "",
     columnname: "",
   },
   {
     id: id_2,
     aggregate: X,
     alias: Y,
     tablename: "",
     columnname: "",
   },
];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.