Json.loads () does not support ordering

I formatted my string to look like JSONso that I can do json.loads. When I typed on the screen, it turned out that it ruined the order. I know Python dictators are not ordered, but is there a way to keep this order? I really need to save this. Thank!

+4
source share
1 answer

Both JSON en Python dictionaries (these are JSON objects) are unordered. So it really makes no sense, because the JSON encoder can reorder.

However, you can define a custom JSON decoder and then parse it using this decoder. Therefore, here the vocabulary hook will be OrderedDict:

from json import JSONDecoder
from collections import OrderedDict

customdecoder = JSONDecoder(object_pairs_hook=OrderedDict)

Then you can decode with:

customdecoder.decode(your_json_string)

, OrderedDict . - , JSON .

loads:

from json import loads
from collections import OrderedDict

loads(your_json_string, object_pairs_hook=OrderedDict)
+6

Source: https://habr.com/ru/post/1688727/


All Articles