[英]Python - Parse requests response
我有一個發布數據的端點。
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'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.