Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Python (http://www.go4expert.com/articles/python-tutorials/)
-   -   Working With JSON in Python (http://www.go4expert.com/articles/json-python-t28859/)

pradeep 10Aug2012 19:31

Working With JSON in Python
 
JSON has now become a extensively used data format, primarily used to exchange data between different systems, you may say that it is a successor of the XML format in this regard. From small to very large web applications use JSON, some still provide XML format as an option while others don't, a few top web companies using JSON format are Facebook, Flickr, Google GData API, etc. So, let's look and working with JSON in Python programs.

Parsing JSON in Python



In Python we will be using the json module for parsing JSON, as a sample JSON we would get the contents of http://graph.facebook.com/pradeep.deepz which looks like this:

Code:

{
  "id": "703880701",
  "name": "Pradeep Deepz",
  "first_name": "Pradeep",
  "last_name": "Deepz",
  "link": "http://www.facebook.com/pradeep.deepz",
  "username": "pradeep.deepz",
  "gender": "male",
  "locale": "en_IN"
}

Code: Python

#!/usr/bin/python

import json

json_str = """{
   "
id": "703880701",
   "
name": "Pradeep Deepz",
   "
first_name": "Pradeep",
   "
last_name": "Deepz",
   "
link": "http://www.facebook.com/pradeep.deepz",
   "
username": "pradeep.deepz",
   "
gender": "male",
   "
locale": "en_IN"
}"
""

print json.loads(json_str)
print
data = json.loads(json_str)
print data["name"]

The output:
Code:

{u'username': u'pradeep.deepz', u'first_name': u'Pradeep', u'last_name': u'Deepz', u'name': u'Pradeep Deepz', u'locale': u'en_IN', u'gender': u'male', u'link': u'http://www.facebook.com/pradeep.deepz', u'id': u'703880701'}

Pradeep Deepz

Create JSON in Python



Creating JSON is as easy as decoding, follow the example code below.

Code: Python

#!/usr/bin/python

import json

data = { "names" : ['Anjali','Pradeep'], "Cities" : ['Mumbai','Kolkata'] }

## output
print json.dumps(data)
## sort output by keys
print json.dumps(data, sort_keys=True)
## pretty printing
print json.dumps(data, sort_keys=True, indent=4)


The output:
Code:

{"Cities": ["Mumbai", "Kolkata"], "names": ["Anjali", "Pradeep"]}
{"Cities": ["Mumbai", "Kolkata"], "names": ["Anjali", "Pradeep"]}
{
    "Cities": [
        "Mumbai",
        "Kolkata"
    ],
    "names": [
        "Anjali",
        "Pradeep"
    ]
}



All times are GMT +5.5. The time now is 05:22.