user7681184
user7681184

Reputation: 1053

How to maintain dictionary element order in JSON dump in Python

Due to a very helpful person on this site, I have been able to put together a script which takes user names (inputted by user) and then use a loop to append each of those user names to a specific JSON structure. However, I have noticed that the order within my JSON dump is not maintained. For example, here is what my loop and JSON dump looks like:

list_users = []
for user in users:
    list_users.append({"name": user,
                       "member": 123,
                       "comment": "this is a comment"})

json_user_list_encoding = json.dumps(list_users, indent=2)

My print looks like this:

({"member": 123,
  "comment": "this is a comment"
  "name": user
  })

I was wondering if it was possible to maintain the same order in "list_users" when I use the JSON dump. I have looked at this site a bit and from what I have read, I will have to assign keys in order to maintain a specific order. However, I am not sure how to do this being that I only have one JSON object. I hope this make sense. Thanks for the help.

Upvotes: 1

Views: 6328

Answers (1)

wim
wim

Reputation: 362607

If you just want them ordered reliably/repeatably, but don't care about the order itself, then json dumps accepts a sort_keys kwarg that can help:

>>> json.dumps({'z': 3, 'b': 2, 'a': 1})
'{"a": 1, "z": 3, "b": 2}'
>>> json.dumps({'z': 3, 'b': 2, 'a': 1}, sort_keys=True)
'{"a": 1, "b": 2, "z": 3}'

Otherwise, put the users in an OrderedDict instead of a plain dict.

from collections import OrderedDict

list_users.append(OrderedDict([
    ("name", user),
    ("member", 123),
    ("comment", "this is a comment"),
]))

If you need them to deserialize to the same order too, use the object_pairs_hook when loading.

Upvotes: 8

Related Questions