0

It is needed to read json file and write it back with uppedned changes into the end of file. For example:

//original
{"k1": "v1", "k4": "v4"}

do some magic and get:

//output
{"k1": "v1", "k4": "v4", "k2": "v2"} 

The big problem here is JSON.stringify() / JSON.parse() call does not garantee en order of json jey during parse / stringify - so json is read into unordered map and written into unordered map again.

Can this be with javascript???

Cherry
  • 31,309
  • 66
  • 224
  • 364
  • Is that really an issue since you can still access your member with `myObj.k1`, `myObj.k4`, `myObj.k2` no matter what their order is ? – Cid May 14 '19 at 13:37
  • 1
    Related to "https://stackoverflow.com/questions/32006162/keep-order-of-objects-inside-a-json-string-after-they-are-parsed" – Yan Foto May 14 '19 at 13:37

2 Answers2

0

Use reviver argument of JSON.parse to remember keys order and then use it to reestablish the order using the replacer argument of JSON.stringify:

let src = '{"y":1,"z":2,"x":3}'
let keysOrder = []
JSON.parse(src, (key, value) => {keysOrder.push(key); return value})
let res = JSON.stringify({z: 1, y: 2, x: 3}, keysOrder)
console.log(res)
Yan Foto
  • 10,850
  • 6
  • 57
  • 88
-1

Maps/Objects attributes in Javascript are unordered. So direct answer is : you can't.

Now you can try to mitigate this by using an array :

[{"k1": "v1"}, {"k2": "v2"}, etc...]

You can create and sort this array before the stringify, and re-assemble the object after the parse.

HRK44
  • 2,382
  • 2
  • 13
  • 30
  • This doesn't answer the question. The question explicitly asks for order **after** being serialized. – Yan Foto May 14 '19 at 13:45
  • I quite don't understand your comment, if you serialize an array and parse it, the order will be kept. – HRK44 May 14 '19 at 13:47
  • That is correct. But its not about order in arrays, but order of **serialized** keys of an object. – Yan Foto May 14 '19 at 14:00
  • OP is also talking about the `parse` function and not only about the serialize part, which once parsed, no order will be guaranteed. If it's just about the serialized string output, your answer is correct. – HRK44 May 14 '19 at 14:04
  • You are right. This is also solvable when using `JSON.parse` (see my answer) – Yan Foto May 14 '19 at 14:25