A
A
a2020-05-06 15:51:03
Python
a, 2020-05-06 15:51:03

How to fix sorting in JSON?

When I change the JSON file and save it, it is sorted alphabetically, which is not usual for me.
JSON

{
   "a": {
        "a": "a",
        "g": "g",
        "b": "b"
    }
}


After saving:
{
   "a": {
        "a": "asasas",
        "b": "b",
        "g": "g"
    }
}


I save like this
with open("file.json") as f:
    a = json.load(f)

with open("file.json", "w") as f:
    a["a"]["a"] = "asasas"
    json.dump(info, f, indent=2, ensure_ascii=False)


How to fix it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2020-05-06
@MZOK

Firstly, before Python 3.7, there was no concept of the order of keys in the dictionary (I myself was surprised when I found out).
Secondly, there is a parameter in the documentation:
json.dump(... ,sort_keys=False)

S
Sergey Gornostaev, 2020-05-06
@sergey-gornostaev

There is no way to fix it, the json format does not guarantee that the order of the keys will be preserved.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question