Closed Kounavi closed 9 years ago
Yes you can. There is an option, sort_keys, which you may provide to either the decode() or encode() function, or wrappers like encode_to_file().
Use sort_keys=demjson.SORT_PRESERVE to keep the same order. On decode()-ing it will create OrderedDict instances, on encoding it will preserve the order in an OrderedDicts. You can see an example of this in the included self test code (file "test/test_demjson.py"):
def testEncodeDictPreserveSorting(self):
import collections
d = collections.OrderedDict()
d['X'] = 42
d['A'] = 99
d['Z'] = 50
self.assertEqual(demjson.encode( d, sort_keys=demjson.SORT_PRESERVE ),
'{"X":42,"A":99,"Z":50}')
The various choices are:
There are many many different options that you can provide, not all of which are documented directly in the encode() function's help/docstring. Instead look at the documentation for the "json_options" class — See to 'sort_keys' descriptor (not method): http://deron.meranda.us/python/demjson/demjson-2.2.3/docs/demjson.html#json_options
Did this solve your problem?
Yay! Thanks! Indeed, that did the trick :) Thanks a lot for the immediate response & all the available options for that matter. Much appreciated! :]
I've been trying to find a way for demjson to output it's (key, value) pairs in a file in the order they were inserted but that seems rather impossible even when using an OrderedDictionary.
Sample code:
Output:
Expected output:
where
is a variable user filepath :) ;)It's not a major issue but is there any way to do that using demjson?