python - 无法从 url 获取纯 json

标签 python json python-3.x web-scraping

我已经用 python 编写了一个脚本来从 url 获取响应,以便我以后可以使用它。我希望得到的响应是 json。但是,我得到的更像是 json:

{"DISPLAY":{"ADA":{"EUR":{"PRICE":"€ 0.07575","SPRICE":"€ 0.08","CHANGE24HOUR":"€ -0.011","CHANGEPCT24HOUR":"-12.58","CLOSED":"€ 0.08","DAY":-12.290825158684369,"HIGH24HOUR":"€ 0.087","LOW24HOUR":"€ 0.072","MKTCAP":"€ 1963975593.25","MKTCAP_ROUND":"€ 1.96 B","MONTH":27.26481127968117,"OPEN24HOUR":"€ 0.08665","SUPPLY":"ADA 25.93 B","TIMESTAMP":1559305128,"VOLUME24HOUR":"ADA 22.74 M","VOLUME24HOURTO":"€  1.78 M","WEEK":9.685520068120473,"DATA_PROVIDER":2}

到目前为止我已经写了:

import json
import requests

url = 'https://ticker.cointelegraph.com/tickers'

res = requests.get(url)
print(res.text)

#the following line throws an error
print(json.loads(res.text))

使用 json.loads(),我得到以下错误:

    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 14796 (char 14795)

如何从该 url 获取纯 json 内容?

最佳答案

如果您查看 res.text 的内容,或页面 https://ticker.cointelegraph.com/tickers 的内容,有一个 +Inf 在导致错误的字符串中,也许用可解析的对象替换它,例如字符串 +Inf 或数字 0

import json
import requests

url = 'https://ticker.cointelegraph.com/tickers'

res = requests.get(url)

#Replaced the +Inf with +Inf string
json_obj = json.loads(res.text.replace('+Inf','"+Inf'))

#Or replace the +Inf with 0 string                  
#json_obj = json.loads(res.text.replace('+Inf','0'))

然后 json_obj 将得到您预期的输出

关于python - 无法从 url 获取纯 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56395380/

相关文章:

python - 卸载Kivy中的音频样本

python - iOS 和 Python 之间的共享二进制格式

Python:这种 {} 格式如何提取正确的数据?

json - Angular 4 + Express 未在 Heroku 上启动

php - mysql_fetch 不显示

javascript - 尝试通过 json 在 html 页面中显示 NEO4J 数据

python - 在 getopt 命令中查找多个参数 Python 3

python-3.x - TensorFlow 0.12 教程产生警告 : "Rank of input Tensor should be the same as output_rank for column

python-3.x - 如何在 Windows 10 上安装 HDF5 版本 1.10.5

python - Python 上的 Tkinter 显示某些(单色)图像困惑