【问题标题】:Unable to get pure json from a url无法从 url 获取纯 json
【发布时间】:2019-10-17 02:54:06
【问题描述】:

我在 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 内容?

【问题讨论】:

  • json 无效。在第 682 行中出了点问题。 --> "DAY": +Inf,

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


【解决方案1】:

如果您查看res.text 的内容或页面https://ticker.cointelegraph.com/tickers 的内容,则字符串中有一个+Inf 会导致错误,可能将其替换为可解析的对象,例如字符串@987654324 @或号码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就会有你预期的输出

【讨论】:

    猜你喜欢
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2013-07-14
    • 2014-07-12
    相关资源
    最近更新 更多