python 解析jsonp,Django-解析JSONP(带有填充的Json)

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)

解决方案

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)[1].strip(")") # convert to json

>>> data_json

'{"key": "val"}'

>>>

>>> json.loads(data_json)

# success

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值