Chemical Programmer Chemical Programmer - 3 months ago 11
Python Question

Django - Parse JSONP (Json with Padding)

I'm using JSONP to send data from

otherdomain.com
to
mydomain.com


However, I got errer when I tried to parse JSONP data in django controller (
views.py
).

Here is my code.




Javascript in
mydomain.com
client page

jsonData = {
'foo': 'bar',
}

$.ajax({
url: 'http://otherdomain.com/end_point/',
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: jsonData,
dataType : 'jsonp',
jsonp : 'callback'
});





Django controller (
views.py
) in
mydomain.com


from django.http import JsonResponse
import json

def decode_jsonp(request):

if 'callback' in request.GET:
json_object = json.loads(request.body) # Raise error
json_object = json.dumps(request.body) # Do not raise error but returns nothing
json_object = json.loads(json.dumps(request.body)) # Raise error

foo = json_object['foo']

return JsonResponse({'foo': foo})


I don't know what should I substitue for
json_object = json.loads(request.body)

Answer

A JSONP object has parentheses around it and a callback. But Python's json module doesn't recognise a JSONP object. So, you'll have to first convert it to JSON object by removing the surrounding parentheses and the callback name.

Example

>>> data = 'callback({"key": "val"})' # a common JSONP object
>>>
>>> json.loads(data)
# raises ValueError
>>>
>>> data_json = data.split("(")[1].strip(")") # convert to json
>>> data_json
'{"key": "val"}' 
>>>
>>> json.loads(data_json)
# success