How to consume JSON response in Python?
Question: I am creating a Django web app. There is a function which creates a JSON
response like this:

    
    
    def rest_get(request, token):
        details = Links.get_url(Links, token)
        result={}
        if len(details)>0:
                result['status'] = 200
                result['status_message'] = "OK"
                result['url'] = details[0].url
        else:
                result['status'] = 404
                result['status_message'] = "Not Found"
                result['url'] = None
    
        return JsonResponse(result)

And I get the response in the web browser like this:

    
    
    {"status": 200, "url": "http://www.bing.com", "status_message": "OK"}
    

Now from another function I want to consume that response and extract the data
out of it. How do I do it?


Answer: You can use the `json` library in python to do your job. for example :

    
    
    json_string = '{"first_name": "tom", "last_name":"harry"}'
    import json
    parsed_json = json.loads(json_string)
    print(parsed_json['first_name'])
    "tom" 
    

Since you have created a web app. I am assuming you have exposed a URL from
which you can get you JSON response, for example
<http://jsonplaceholder.typicode.com/posts/1>.

    
    
    import urllib2
    import json
    data = urllib2.urlopen("http://jsonplaceholder.typicode.com/posts/1").read()
    parsed_json = json.loads(data)
    

The `urlopen` function sends a `HTTP GET` request at the given URL.
`parsed_json` is a variable of the type map and you can extract the required
data from it.

    
    
    print parsed_json['userId']
    1
    

