Friday, May 22, 2009

python: simple start with simplejson

JSON (i.e. JavaScript Object Notation) is a popular way of exchanging data in a string format. It can also be used to provide setup parameters for a program. The second option I used to show very basic JSON usage in python with simplejson package. Lets assume that we have a txt file called data.json with the following JSON code:{
"Name": "W",
"Job": "Programmer",
"Movies": ["Star Wars", "Star Trek", "Terminator"],
"Address" : {
"Street": "Some Streat",
"House": 3,
"City": "Some City"
}
}
The above JSON code can be read into python object using load function as followsIn [7]: import simplejson as json
In [8]: f=open("data.json")
In [9]: data=json.load(f)
In [10]: f.close()
In [11]: data
Out[11]:
{'Address': {'House': 3, 'Street': 'Some Streat', 'City': 'Some City'},
'Job': 'Programmer',
'Movies': ['Star Wars', 'Star Trek', 'Terminator'],
'Name': 'W'}
In [12]: print data['Address']['House']
3
In [13]:
That's it:-)

No comments:

Post a Comment