0

I created a ordered dict in Python 2.7. I then insert key,value pairs. The ordered dict keeps the order in which i insert the keys.

Now i use dump() to write this to a file and all of sudden the order is messed up. I know that json does not care about order, but i read that with ordereddict it should somehow work too?

Maybe just inserting is not enough, do i need to create a custom sort order based on what now is my insert order? So is there any hope?

Edit I found out that everything is right with python. It was the program to view the json after saving which disturbed the order.

apfel
  • 33
  • 6
  • unless you want json you can pickle, also I presume you mean dump nor dumps – Padraic Cunningham Jan 30 '15 at 01:06
  • I need JSON and i use dump to write to a file – apfel Jan 30 '15 at 01:21
  • Note that JSON collections are unordered, so there's no "correct" ordering of key/value pairs inside one. You can't depend on any given JSON parser to respect the order that you've written data out. Your viewer is completely within spec to present items in alphabetical, reversed, or any other sorting. – Kirk Strauser Jan 30 '15 at 01:32
  • @KirkStrauser yes you are right, one thing you could to is to use dump(intend=2) and after that use gzip to zip the file. Then the file is very small and if you want to view, you are not dependent on a json-viewer because it is already preformated and you can view it with any editor. – apfel Jan 30 '15 at 01:58

1 Answers1

1

If you're using the collections.OrderedDict class, json.dumps should already observe ordered output. I just tried doing a quick test locally, and had success:

>>> import collections
>>> import json
>>> d = collections.OrderedDict()
>>> d['foo'] = 'bar'
>>> d['baz'] = 'quux'
>>> json.dumps(d)
'{"foo": "bar", "baz": "quux"}'
>>> d['wat'] = 'waaaaat'
>>> json.dumps(d)
'{"foo": "bar", "baz": "quux", "wat": "waaaaat"}'
>>> d['baz'] = 'qux'
>>> json.dumps(d)
'{"foo": "bar", "baz": "qux", "wat": "waaaaat"}'
>>> d[123] = 456
>>> json.dumps(d)
'{"foo": "bar", "baz": "qux", "wat": "waaaaat", "123": 456}'

If you're not seeing this behavior, do you mind providing a sample that exhibits the undesirable behavior?

bmhkim
  • 754
  • 5
  • 16
  • 1
    Also, because you'll want to import in ordered fashion, you might want to check out [how to load into an ordereddict from json](http://stackoverflow.com/questions/6921699/can-i-get-json-to-load-into-an-ordereddict-in-python). – bmhkim Jan 30 '15 at 01:01
  • the problem occurs when writing to a file. when outputting to the console everythings ok. – apfel Jan 30 '15 at 01:09
  • Seems okay to me, and you accepted the solution. Does this mean everything seems to be working correctly now? – bmhkim Jan 30 '15 at 01:55
  • yes as i mentioned there was nothing wrong with the code it was just the program to view the jsonfile which used its own order – apfel Jan 30 '15 at 01:56