I have an object which I'm trying to write into a json file like this:
let sample_obj={k:v,items:{a:1,b:2,d:4}};
sample_obj['items']['c']=3;
fs.writeFile('data.json',JSON.stringify(sample_obj));
but when I open the data.json file it shows:
{k:v,items:{a:1,b:2,d:4,c:3}}
but I need the order to be items:{a:1,b:2,c:3,d:4} but it seems that the order that is written into the file is same as the order in which the key and pair was added
is there anyway to write into the file ordered?
Of course there is if you are willing to serialize it yourself. But fields in JSON objects are, by definition, not ordered. So if you are thinking of this indeed as a JSON file, then there is no point in writing it ordered, because anyone reading the file should not rely on the serialization order either. If one was pedantic, one could even say that your file wouldn't be JSON anymore if the order mattered -- and only look misleadingly similar.
Long story short: don't do it. If you absolute need something to be ordered, make it an array, e.g.:
items: [
{key: 'a', value: 1},
{key: 'b', value: 2},
{key: 'c', value: 3},
{key: 'd', value: 4}
]