我有一个发布数据的端点。
r = requests.post(url, data=data, headers=headers)
我在 Javascript 中得到以下响应:-
throw 'allowScriptTagRemoting is false.';
(function() {
var r = window.dwr._[0];
//#DWR-INSERT
//#DWR-REPLY
r.handleCallback("1", "0", {
msg: "",
output: {
msg: "Showing from city center",
resultcode: 1,
scrpresent: true,
srclatitude: "28.63244546123956",
srclongitude: "77.21981048583984",
},
result: "success"
});
})();
如何解析响应?我基本上想要 output
json。我怎样才能得到同样的东西?
最佳答案
问题是 - output
不是有效的 JSON 字符串,无法通过 json.loads()
加载。
我将使用正则表达式来定位 output
对象,然后使用 findall()
来定位键值对。示例工作代码:
import re
data = """
throw 'allowScriptTagRemoting is false.';
(function() {
var r = window.dwr._[0];
//#DWR-INSERT
//#DWR-REPLY
r.handleCallback("1", "0", {
msg: "",
output: {
msg: "Showing from city center",
resultcode: 1,
scrpresent: true,
srclatitude: "28.63244546123956",
srclongitude: "77.21981048583984",
},
result: "success"
});
})();
"""
output_str = re.search(r"output: (\{.*?\}),\n", data, re.DOTALL | re.MULTILINE).group(1)
d = dict(re.findall(r'(\w+): "?(.*?)"?,', output_str))
print(d)
打印:
{'msg': 'Showing from city center', 'resultcode': '1', 'srclongitude': '77.21981048583984', 'srclatitude': '28.63244546123956', 'scrpresent': 'true'}
关于javascript - Python-解析请求响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35523766/