Chemical Programmer Chemical Programmer - 1 year ago 240
Python Question

Django - Parse JSONP (Json with Padding)

I'm using JSONP to send data from

However, I got errer when I tried to parse JSONP data in django controller (

Here is my code.

Javascript in
client page

jsonData = {
'foo': 'bar',

url: '',
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: jsonData,
dataType : 'jsonp',
jsonp : 'callback'

Django controller (
) in

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 Source

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.


>>> 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download