python - Django - Parse JSONP (Json with Padding) -
i'm using jsonp send data otherdomain.com
mydomain.com
however, got errer when tried parse jsonp data in django controller (views.py
).
here 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) # not raise error returns nothing json_object = json.loads(json.dumps(request.body)) # raise error foo = json_object['foo'] return jsonresponse({'foo': foo})
i don't know should substitue json_object = json.loads(request.body)
a jsonp object has parentheses around , callback. python's json
module doesn't recognise jsonp object. so, you'll have first convert json object removing surrounding parentheses , callback name.
example
>>> data = 'callback({"key": "val"})' # common jsonp object >>> >>> json.loads(data) # raises valueerror >>> >>> data_json = data.split("(")[1].strip(")") # convert json >>> data_json '{"key": "val"}' >>> >>> json.loads(data_json) # success
Comments
Post a Comment