Last active
February 23, 2024 17:40
-
-
Save tuxfight3r/fdb2d6dfcc9b316ef623 to your computer and use it in GitHub Desktop.
python json read and sort dictionary list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
#Date: 05/03/2016 | |
#Author: Mohan Balasundaram | |
#Purpose: To read a json file with a dictionary list and sort the output | |
import json | |
import sys | |
json_filename=sys.argv[1] | |
#print json_filename | |
try: | |
json_file=open(json_filename) | |
json_data=json.load(json_file) | |
except IOError: | |
print "Error: File does not appear to exist." | |
finally: | |
json_file.close() | |
my_dict={} | |
for item in json_data['result']: | |
#print item['templateid'], ": ",item['name'] | |
my_dict.update({ item['templateid']: item['name']}) | |
for key in sorted(my_dict.iterkeys()): | |
print "%s: %s" % (key, my_dict[key]) | |
""" | |
#sample data structure | |
{ | |
"id": 1, | |
"jsonrpc": "2.0", | |
"result": [ | |
{ | |
"name": "linux", | |
"templateid": "10" | |
}, | |
{ | |
"name": "windows", | |
"templateid": "100" | |
}, | |
] | |
} | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment