0

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?

Zizouz212
  • 4,908
  • 5
  • 42
  • 66
anirban.at.web
  • 349
  • 2
  • 11

2 Answers2

1

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
Kiran Yallabandi
  • 2,544
  • 2
  • 22
  • 25
1

The answer I want to suggest is a little different. In your scenario - where one function needs to be accessed from both server and client end, I would suggest provide some extra parameter and change the output based on that. This reduces overheads and unnecessary conversions.

For example, if you pass in an extra parameter and change the result like this, you don't need JSON parsing on python. Of course there are solutions to do that, but why need converting to json and then parsing back when you can avoid that totally?

def rest_get(request, token, return_json=True):

    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
    if return_json: # this is web response, so by default return_json = True
        return JsonResponse(result)
    return result

Then in your python code call like this -

rest_get(request, token, return_json=False): # we are passing False, so the return type is dictionary and we can use it right away.
brainless coder
  • 6,310
  • 1
  • 20
  • 36