Reputation: 1157
I'm trying to build a JSON string using json python module.
In particular I want this structure:
data = {
'Id' : deviceId,
'UnixTime' : unixTime,
'Temp' : round( temperature, 2 ),
'Rh' : round( humidity,2 ),
}
But when I execute: jsonString = json.dumps( data )
All field are scrambled.
Any Suggestion?
Upvotes: 1
Views: 816
Reputation: 2847
Both Python dict and JSON object are unordered collections.
Use the sort_keys parameter, to sort the keys:
>>> import json
>>> json.dumps({'a': 1, 'b': 2})
'{"b": 2, "a": 1}'
>>> json.dumps({'a': 1, 'b': 2}, sort_keys=True)
'{"a": 1, "b": 2}'
If you need a particular order; you could use collections.OrderedDict:
>>> from collections import OrderedDict
>>> json.dumps(OrderedDict([("a", 1), ("b", 2)]))
'{"a": 1, "b": 2}'
>>> json.dumps(OrderedDict([("b", 2), ("a", 1)]))
'{"b": 2, "a": 1}'
Upvotes: 3