在处理Binance公共API的JSON响应时,需要使用JSON库将响应字符串转换为JSON格式并进行处理。以下示例代码演示如何使用Python中的json库解析Binance API响应。
import json
import requests
response = requests.get('https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT')
json_response = json.loads(response.text)
if 'code' in json_response:
print('Error:', json_response['msg'])
else:
print('BTC price:', json_response['price'])
在这个例子中,我们使用requests
库从Binance API获取BTC/USDT的最新价格。然后,将响应字符串转换为JSON格式,以便于读取和处理。最后,我们检查JSON响应是否包含错误代码和错误消息,并输出BTC价格。
需要注意的是,Binance API响应中可能包含的错误代码和错误消息,我们需要根据实际情况进行处理。