Skip to content

Instantly share code, notes, and snippets.

@tuxfight3r
Last active February 23, 2024 17:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tuxfight3r/fdb2d6dfcc9b316ef623 to your computer and use it in GitHub Desktop.
Save tuxfight3r/fdb2d6dfcc9b316ef623 to your computer and use it in GitHub Desktop.
python json read and sort dictionary list
#!/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