Skip to content

Instantly share code, notes, and snippets.

@powerlim2
Created May 21, 2013 19:32
Show Gist options
  • Save powerlim2/5622537 to your computer and use it in GitHub Desktop.
Save powerlim2/5622537 to your computer and use it in GitHub Desktop.
This code shows the procedure of how to work with .json files using Python.
## 05. 05. 2013
## Author: Joon Lim
## JSON file handling
import json
jsfile = open('/Users/joonhyunglim/Desktop/Python/json_handling/glyph_json_data.txt')
data = json.load(jsfile)
jsfile.close()
# change the 'list' to 'dictionary' type
for i in range(0, len(data)):
glyph[i] = dict(data[i])
#check the length of glyph
len(glyph)
# from now on, I further investigate glyph[0].
# brief check for the key value of each data in glyph[0].
for i in glyph[0].keys():
print i,":", glyph[i].__class__
# UDF for further investigating its sub-hierarchies
def sub_hier(data):
''' perform sub hierachy investigation'''
if isinstance(data, dict):
print "this key is dictionary type and have keys below:\n",data.keys()
elif isinstance(data, list):
print "this key is list type and have:",len(data),"values."
else:
print "this key doesn't have any sub-hierarchys."
return ''
# now further investigation
for i in glyph[0].keys():
print "for key '{0}',\n".format(i),"\t",sub_hier(glyph[0][i])
# now go further for the 'creditCards'
glyph[0]['creditCards'].__class__ # confirm it's list type!
# investigate the list
for i in range(0,len(glyph[0]['creditCards'])):
print "for key '{0}',\n".format(i),"\t",sub_hier(glyph[0]['creditCards'][i])
# now further investigative for the first list value (dictionary type)
for i in glyph[0]['creditCards'][0].keys():
print "for key '{0}',\n".format(i),"\t",sub_hier(glyph[0]['creditCards'][0][i])
## we can do this for all 22 dictionarys e.g. glyph[0] ~ glyph[22]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment