How to write to .json file in order?

Solution 1:

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}
]