Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
How to write to .json file in order?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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}
]
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!