处理调用 `request.get(…).json()` 时的转义字符。

huangapple go评论61阅读模式
英文:

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&quot;&quot;&quot;{
  &quot;text&quot;: {
    &quot;div&quot;: &quot;&lt;div xmlns=\&quot;http://www.w3.org/1999/xhtml\&quot;&gt;&lt;/div&gt;&quot;
  }
}&quot;&quot;&quot;

data = json.loads(request_get)
print(data)

output:

{&#39;text&#39;: {&#39;div&#39;: &#39;&lt;div xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;&lt;/div&gt;&#39;}}

huangapple
  • 本文由 发表于 2023年6月15日 23:49:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483424.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定