Python 没有读取有效的 JSON

标签 python html json string encoding

我正在从网页中抓取一些 HTML 源代码以提取以 json 格式存储的数据

这是代码:

url = 'https://finance.yahoo.com/quote/SPY'
result = requests.get(url)

c = result.content
html = BeautifulSoup(c, 'html.parser')
scripts = html.find_all('script')

sl =[]
for s in scripts:

     sl.append(s)

s = (sl[-3])
s = s.contents
s = str(s)
s = s[119:-16]

json_data = json.loads(s)

运行上面的代码会抛出这个错误:

json.decoder.JSONDecodError: Expecting ',' delimiter: line 1 column 7506 (char7505)

当我获取变量 s 的内容并将其传递给 json 格式化程序时,它被识别为正确的 json。

我使用以下网站检查 json: http://jsonprettyprint.com/json-pretty-printer.php

为什么在 Python 中使用 json.loads() 时会出现此错误?我假设它与未正确编码的字符串或存在转义字符有关?

我该如何解决?

最佳答案

您的 JSON 包含某些意外标记,例如 true。先用json.dumps解决。

print (json.dumps(s,indent =2))
s = json.dumps(s)
json_data = json.loads(s)

关于Python 没有读取有效的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55056192/

相关文章:

python - Python 中字符串排序与自定义哈希函数的性能比较

python - 从 MYSQL 读取模型时出现 DjangoUnicodeDecodeError

PHP 代码没有从 POST 提交数据

javascript - Vue js v-if 在共享切换按钮上进行条件渲染

python - DataFrame 到嵌套 JSON

python - 表示文本中后续更改并使用 Python 使用此表示的标准方法是什么?

python - MySQLdb无法初始化字符集utf-8错误

javascript - Bootstrap Flash 警报 CSS 在移动屏幕上无法正常工作

jquery - Bootstrap-toggle 变得又大又丑。为什么?

json - 更新 postgres 中的 json 数组