英文:
Handling escape characters when calling `request.get(...).json()`
问题
我正在使用一个第三方API,该API的响应中包含HTML转义字符,这导致调用以下代码时出现错误:
request_get = request.get(...)
request_get.json()
我已经将错误简化到以下最简单的形式,以展示错误的来源示例。请注意,在这种情况下,request_get
是一个请求对象:
request_get = """{
"text": {
"div": "<div xmlns=\"http://www.w3.org/1999/xhtml\"></div>"
}
}"""
json.loads(request_get)
输出:
JSONDecodeError: Expecting ',' delimiter: line 3 column 25 (char 38)
如何处理这种类型的返回是最佳方式?请注意,错误来自\"
。非常感谢!
英文:
I'm working with a third party API that will include HTML escape characters within the response, which is causing an error of Expecting ',' delimiter:
when calling the below:
request_get = request.get(...)
request_get.json()
I've filtered down the error to the simplest form below to show an example of what the error is coming from. Note that request_get in this case is a request object:
request_get = """{
"text": {
"div": "<div xmlns=\"http://www.w3.org/1999/xhtml\"></div>"
}
}"""
json.loads(request_get)
Output:
JSONDecodeError: Expecting ',' delimiter: line 3 column 25 (char 38)
What is the best way to deal with this type of return? Note the error comes from \"
Many thanks in advance!
答案1
得分: 1
为了解决这个问题,你可以使用原始字符串格式(通过在字符串前面加上r)来确保转义字符被视为文字。
import json
request_get = r'''{
"text": {
"div": "<div xmlns=\"http://www.w3.org/1999/xhtml\"></div>"
}
}'''
data = json.loads(request_get)
print(data)
输出:
{"text": {"div": "<div xmlns=\"http://www.w3.org/1999/xhtml\"></div>"}}
英文:
To resolve this issue, you can use raw string format (by prefixing the string with r) to ensure the escape characters are treated as literals
import json
request_get = r"""{
"text": {
"div": "<div xmlns=\"http://www.w3.org/1999/xhtml\"></div>"
}
}"""
data = json.loads(request_get)
print(data)
output:
{'text': {'div': '<div xmlns="http://www.w3.org/1999/xhtml"></div>'}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论