[英]How can I create a Python dict from a JSON object that contains escaped double quotes?
In Python, if I receive this response from an API (via Python's "requests" module):在 Python 中,如果我从 API 收到此响应(通过 Python 的“请求”模块):
{"key": "<a href=\"www.foobar.com\""}
How can I convert it to a Python dict?如何将其转换为 Python 字典?
If I use json.dumps, for example:如果我使用 json.dumps,例如:
request = requests.get(url, headers=headers)
request_text = request.text
json_output = json.loads(request_text)
I receive the following error:我收到以下错误:
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 19 (char 18)
with reference to your response {"key": "<a href="www.foobar.com""}, I test with following method.参考您的回复 {"key": "<a href="www.foobar.com""},我使用以下方法进行测试。
import json request_text = {"key": "<a href=\"www.foobar.com\""}
json_output = json.dumps(request_text)
a = json.loads(json_output)
print(a.get("key"))
expected result: <a href="www.foobar.com"预期结果:<a href="www.foobar.com"
There are two solutions:有两种解决方案:
request.json()
instead of request.text
使用request.json()
而不是request.text
r'{"key": "<a href=\\"www.foobar.com\\""}'
, using any unicode encoding methods.将其转换为原始字符串r'{"key": "<a href=\\"www.foobar.com\\""}'
,使用任何 unicode 编码方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.