1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Working With JSON in Python

Discussion in 'Python' started by pradeep, Aug 10, 2012.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    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:
    #!/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:
    #!/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"
        ]
    }
    
     

Share This Page