tonemgub tonemgub - 9 days ago 6
JSON Question

How to print sorted data on json.load?

I need to print line for line a static json file. I would like to sort this by a key value prior to printing. I have looked at several other examples on stackoverflow, but was unable to find a solution to this particular problem.

My code so far looks like this:

import json
from pprint import pprint
with open('items.json') as data_file:
data = json.load(data_file)
for line in data:
pprint(data)


My json looks like this:

[
{"version": ["2.8.2"], "license": ["GPL"]},
{"version": ["1.8.8"], "license": ["MIT/X11 License"]},
{"version": ["2.8.5"], "license": ["GPL"]},
{"version": ["1.8.9"], "license": ["MIT/X11 License"]}
]


How can I sort it by a key value such as "version" while preserving order?
In this way I can determine at which version the license was changed.

Desired output would look like this:

[
{"version": ["1.8.8"], "license": ["MIT/X11 License"]},
{"version": ["1.8.9"], "license": ["MIT/X11 License"]},
{"version": ["2.8.2"], "license": ["GPL"]},
{"version": ["2.8.5"], "license": ["GPL"]}
]


Thank you.

Answer

It looks like the data is already in dictionary form so something like:

sorted_data = sorted(data, key = lambda x: x['version'])

And then pretty-print that structure.

Edit: you can print the whole structure with one line, by the way:

pprint.pprint(sorted_data, indent=4)

should look pretty nice.

For more information on the lambda expression, have a look at this SO thread: What is key=lambda