Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda