worenga
worenga

Reputation: 5856

python json keep object order on output

class MessageCreator:

    def serialize(self,obj):
        return json.dumps(obj,sort_keys=False,indent=None, separators=(',', ':'))

    def createGroup(self,name,description,masterkey):
        return self.serialize({
                               'typ':str(types.CREATE_GROUP),
                               'group':[{
                                        'name':str(name),
                                        'descr':str(description),
                                        'mk':str(masterkey)
                                        }]
                            })

will return

{"group":[{"mk":"test","name":"test","descr":"test"}],"typ":"517"}

however i want the order to be kept intact like

{"typ":"517","group":[{"name":"test","descr":"test","mk":"test"}]}

How to achieve this?

Upvotes: 0

Views: 1580

Answers (6)

manjy
manjy

Reputation: 109

As of Python 3.7, dictionaries will retain its order. From Python 3.7 Changelog

the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec.

Upvotes: 0

Sar009
Sar009

Reputation: 2276

change serialize() as follow

from collections import OrderedDict
order=["typ", "group"]
def serialize(obj):
    temp_list=OrderedDict()
    for each_order in order:
        temp_list[each_order]=obj[each_order]
    return json.dumps(temp_list)

Upvotes: 0

Tupteq
Tupteq

Reputation: 3095

You have to use OrderedDict, not a normal dict, because dict doesn't preserve order.

import json
from collections import OrderedDict

a = {'c':3, 'a':1, 'b':2}
print(json.dumps(a)) # Random order: a,c,b for example
a = OrderedDict([('c', 3), ('a', 1), ('b', 2)])
print(json.dumps(a))  # Desired order: c,a,b

Upvotes: 2

venpa
venpa

Reputation: 4318

you can do this:

import collections
data = (("typ","517"),
    ("group",[{"mk":"test","name":"test","descr":"test"}]))
od = collections.OrderedDict(data)

Upvotes: 1

iurisilvio
iurisilvio

Reputation: 4987

Use an OrderedDict instead of a normal dict.

import json
from collections import OrderedDict

print json.dumps(OrderedDict([('a', 1), ('b', 2)]))

Upvotes: 1

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72755

If you want order, use a list([]). If you want random access, use a table({}). You can keep a list of keys in order as a separate attribute and then resort by that after you read out the data.

Upvotes: 1

Related Questions