0
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?

8
  • 2
    Python dictionaries nor JSON objects have a defined order. They are always ordered arbitrarily. Why do you have to have a fixed order, what is your use case? Commented Feb 11, 2014 at 12:32
  • i specify a fixed order in a specification in order to compute signatures of payloads. Commented Feb 11, 2014 at 12:34
  • Then set sort_keys=True to ensure a stable key order. It doesn't matter to the consumer of this JSON what the order is, because they are allowed to use any order they like for the keys too. Commented Feb 11, 2014 at 12:36
  • 2
    or make your signature computer smarter about key ordering. Don't try to bend the JSON standard around this use-case. Commented Feb 11, 2014 at 12:37
  • 1
    @Tupteq: the JSON standard states that JSON objects use arbitrary order. The fact that the encoder just loops over dictionary items when encoding is merely a implementation detail. Commented Feb 11, 2014 at 12:41

6 Answers 6

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

Use an OrderedDict instead of a normal dict.

import json
from collections import OrderedDict

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

Comments

1

you can do this:

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

Comments

0

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)

1 Comment

the order is also required for subdicts
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.