[英]Python - Parse requests response
I've an endpoint where I post the data. 我有一个发布数据的端点。
r = requests.post(url, data=data, headers=headers)
I get the following response in Javascript:- 我在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"
});
})();
How do I parse the response? 如何解析响应? I basically want the
output
json. 我基本上想要
output
json。 HOw can I get the same? 我怎么能得到相同的?
The problem is - output
is not a valid JSON string and cannot be loaded via json.loads()
. 问题是-
output
不是有效的JSON字符串,无法通过json.loads()
加载。
I would use regular expressions to locate the output
object and then use findall()
to locate key-value pairs. 我将使用正则表达式来定位
output
对象,然后使用findall()
来定位键值对。 Sample working code: 示例工作代码:
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)
Prints: 打印:
{'msg': 'Showing from city center', 'resultcode': '1', 'srclongitude': '77.21981048583984', 'srclatitude': '28.63244546123956', 'scrpresent': 'true'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.