首页 > 解决方案 > 在python中解析json子类

问题描述

我有一个名为 btc_price() 的函数

def btc_price():
    btc_request = requests.get("https://api.coinbase.com/v2/prices/BTC-USD/buy", timeout=5)
    btc_json = json.loads(btc_request.text)
    print(btc_json['amount'])

这将返回一个错误,coinbases api 的输出是

{"data": {"base": "BTC", "currency": "USD", "amount": "34375.68"}}

它在数据中 - >数量,我将如何访问该数据?我试图从 coinbases api 打印出 btc 价格。

标签: pythonjsonparsing

解决方案


正如您所提到的,假设您要访问的数据的路径是 ,data->amount一种可能的方法是:

def btc_price():
    btc_response = requests.get("https://api.coinbase.com/v2/prices/BTC-USD/buy", timeout=5)
    btc_json = btc_response.json()
    print(btc_json['data']['amount'])

请注意,来自的响应对象requests已经内置json了解析器


推荐阅读