http 请求响应不是 json 格式

http request response not in json format

我花了很多时间试图解决这个问题,但仍然没有成功。如果您能提供帮助,将不胜感激。

这是在Python

当我运行这个:

import requests
import json

response = requests.post(url)
response.text

我明白了:

'\n\n\n\n{\nVisitCount : "9,992",\ntotalCount : "18,018",\nnotiList : [\n\n],\nPassed : false\n}'

如果我运行这个:

print(response.text)

我明白了:

{ VisitCount : "9,992", totalCount : "18,018,455", notiList : [

], Passed : false }

最终我的目标是提取数字 9,992。 我认为最简单的方法是将其转换为 json,但它似乎不起作用。

当我运行:

response.json() or json.loads(response.text)

我明白了:

JSONDecodeError: Expecting property name enclosed in double quotes: line 6 column 1 (char 6)

这可能是因为它在响应中缺少双引号。

  1. 我该如何解决这个问题,可能是在响应中添加双引号?
  2. 是否有更简单的方法来提取数字,在本例中为 9,992?

您可以使用正则表达式:

import re
number_string = re.findall("VisitCount\W+:\W+.*?([0-9,]+).*", response.text.strip())[0]

给出 number_string 作为

9,992

如果要转换成int:

number = int(number_string.replace(",", ""))