How read json file with order garantee in javascript (nodejs)? [duplicate]

45
May 15, 2019, at 6:50 PM

This question already has an answer here:

  • sort object properties and JSON.stringify 18 answers

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???

Answer 1

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)

Answer 2

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.

READ ALSO
puppeteer issue on CentOs 7 problem after exactly 30 minutes

puppeteer issue on CentOs 7 problem after exactly 30 minutes

i have a script that use node js and puppeteer, the script run wonderful on my windows 10 for as long as i dont close it from command line, when i`m using it

26
Deploying a precompiled nodejs function to Azure Functions v2 Syncing 2 function triggers with payload size 317 bytes successful

Deploying a precompiled nodejs function to Azure Functions v2 Syncing 2 function triggers with payload size 317 bytes successful

I have created a Nodejs function app using Visual Studio Code and it runs successfully when I run it on VS Code but when I deploy to Azure portal I get following that syncing 2 function triggers when I have only one

30
unable to get the response in the res.json

unable to get the response in the res.json

I am trying to call sql module inside the sql module and push the second level module into the first level module array so that i can get the resultBut the i getting the null array in the output

17