I have formatted my String to look like JSON
so I could do json.loads
on it. When I printed on the screen it turned out it messed up the order. I know that Python dictonaries are not ordered but is there ANY way to keeps this order? I really need to keep it. Thanks!
Both JSON en Python dictionaries (those are JSON objects) are unordered. So in fact it does not makes any sense to do that, because the JSON encoder can change the order.
You can however define a custom JSON decoder, and then parse it with that decoder. So here the dictionary hook willl be an 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)
This will thus store the items in an OrderedDict
instead of a dictionary. But be aware - as said before - that the order of the keys of JSON objects is unspecified.
Alternatively, you can also pass the hook to the loads
function:
from json import loads
from collections import OrderedDict
loads(your_json_string, object_pairs_hook=OrderedDict)
Update: as of python-3.7, a dictionary retains insertion order. So if one uses python-3.7, the standard
json.load
andjson.loads
should work fine. Note however that a JSON object is still unordered, so that the JavaScript end can load/dump the object in any order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With