Friday, March 6, 2015

py31. Reading a json file in Python

Using the example json file from wikipedia.


The function json.load is used.


A dictionary is read and we can print what are the components of the dictionary. Since a Python dictionary does have any order, it does not list in the order that they are read from the file.


Since len() may not be applied to all types of data, the length is only printed if len() does not return an exception, in which case, it does nothing.

# ex31.py
from __future__ import print_function, division
import json
with open("ex31data.json") as f:
    data = json.load(f)
for k in data:
    print('\n', k, sep='')
    print('type:',type(data[k]))
    try: 
        print('length:',len(data[k]))
    except: pass
    
print("\ndata['phoneNumber']")
for i in data['phoneNumber']:
    print(i)

#firstName
#type: <type 'unicode'>
#length: 4
#
#lastName
#type: <type 'unicode'>
#length: 5
#
#age
#type: <type 'int'>
#
#address
#type: <type 'dict'>
#length: 4
#
#phoneNumber
#type: <type 'list'>
#length: 2
#
#gender
#type: <type 'dict'>
#length: 1
#
#data['phoneNumber']
#{u'type': u'home', u'number': u'212 555-1234'}
#{u'type': u'fax', u'number': u'646 555-4567'}

No comments:

Post a Comment