Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda