xausky
xausky

Reputation: 31

How to keep the order of JSON numeric keys in nodejs

var json = `{"3":0,"2":0,"1":0}`
var obj = JSON.parse(json)
console.log(JSON.stringify(obj))
console.log(json === JSON.stringify(obj))

output

{"1":0,"2":0,"3":0}
false

I expect to get it

{"3":0,"2":0,"1":0}
true

How to do

Upvotes: 1

Views: 2624

Answers (4)

brk
brk

Reputation: 50326

This is because json is an object after parsing and object's keys are not guaranteed to be in order

You can use map & it guarantees the order of the keys

Upvotes: 4

adiga
adiga

Reputation: 35243

That's not possible. In ES6, the keys are traversed in the following order:

  • First, the keys that are integer indices, in ascending numeric order.

  • Then, all other string keys, in the order in which they were added to the object.

  • Lastly, all symbol keys, in the order in which they were added to the object.

The integer keys are sorted in ascending order irrespective of the order in which they are inserted

var a = {};
a[3] = "three"
a[2] = "two"
a[1] = "one"

console.log(JSON.stringify(a))

Reference

You might also want to read: Does JavaScript Guarantee Object Property Order?

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386660

You could spend the keys a dot and by iteratong these keys are in the original insertation order, but not accessable with just the number. This needs a dot as well.

var json = `{"3.":0,"2.":0,"1.":0}`
var obj = JSON.parse(json)

console.log(obj[2])
console.log(JSON.stringify(obj))
console.log(json === JSON.stringify(obj))

Upvotes: 0

AlexOwl
AlexOwl

Reputation: 867

You can use array of objects with guid property

const text = '[{"id":3,"value":0},{"id":2,"value":0},{"id":1,"value":0}]'

const json = JSON.parse(text)

console.log(JSON.stringify(json))

Upvotes: 0

Related Questions