0

In my web application I receive a JSON string from the server which I keep in the greetings variable:

var greetings = '{"2":"hoi","3":"hi","1":"salam"}'

Please notice how the greetings start with the index 2 and the value hoi. Now I want to parse the JSON and the result is the following:

JSON.parse(greetings) // {1: "salam", 2: "hoi", 3: "hi"}

The order has changed, it seems like JSON.parse orders the result by key.

Is there a way to keep the order of the original string intact?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Mister Verleg
  • 4,053
  • 5
  • 43
  • 68

2 Answers2

4
{
   "2":"hoi",
   "3":"hi",
   "1":"salam"
}

is not an array, its an object. Objects don't have any order. If the order is important, you need to switch to an actual array.

str
  • 42,689
  • 17
  • 109
  • 127
Patrick M
  • 113
  • 1
  • 7
  • 2
    W3Schools is wrong... [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – Andreas Mar 26 '18 at 11:39
  • 1
    You'd probably call that a POJO. – H.B. Mar 26 '18 at 11:40
  • 1
    As of ES6/ES2015 there is an order: [javascript - Does ES6 introduce a well-defined order of enumeration for object properties? - Stack Overflow](https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties) – Andreas Mar 26 '18 at 11:45
  • 1
    @Patrick I updated your answer with the correct terminology and better links. Mixing up JSON and objects is a very common mistake (as is calling it "JSON Object", which is wrong). But at least now we know where people get that from... – str Mar 26 '18 at 11:47
  • @str [`[[OwnPropertyKeys]]`](https://www.ecma-international.org/ecma-262/6.0/#sec-ordinary-object-internal-methods-and-internal-slots-ownpropertykeys): 1. integers in ascending order, 2. strings (but not integers) in order of creation, 3. symbols in order of creation - all cases have an order – Andreas Mar 26 '18 at 14:11
  • @Andreas I read your comment wrong, I assumed you are implying it is insertion order. Sorry ;) – str Mar 26 '18 at 14:35
1

You generally cannot rely on the order of indices in an object. Use an array of key/value pairs instead.

As you can see the keys are parsed to (numeric) indices, which is why they are ordered that way. You could hack around this by prefixing your keys and then stripping those later:

console.log(JSON.parse('{"i2":"hoi","i3":"hi","i1":"salam"}'))
H.B.
  • 166,899
  • 29
  • 327
  • 400