所以,根据Python-Binance的文档,我得到的是一个字典JSON响应。当我得到响应时,它看起来像这样:
{'symbol': 'BTCUSDT', 'price': '37256.90000000'}
我要做的就是把它重新格式化,使它看起来像这样:
'$BTC @ 37256.900'
基本上是删除大括号和所有其他不需要的垃圾。
我从Binance API使用Python-Binance的代码和我打印它的方式:
price = client.get_symbol_ticker(symbol="BTCUSDT")
from crypto_tracker import price
print(price)
这可能吗?
Python有一个很棒的库json,可以帮助您获取json字符串并从中创建Python字典。
从你的例子中,我创建了以下代码:
import json
## Given example string
json_string = '{"symbol": "BTCUSDT", "price": "37256.90000000"}'
## Create a python dict from json string using json library json.loads
json_dict = json.loads(json_string)
## What the new python dict looks like:
## json_dict = {'symbol': 'BTCUSDT', 'price': '37256.90000000'}
## Print your expected output
print(f'$BTC @ {json_dict["price"]}')
打印输出:
$BTC @ 37256.90000000
使用python "json"Library将自动将json字符串转换为python字典,然后您可以以任何方式使用它(即自动删除所有额外的"括号和…其他不需要的垃圾。")。
编辑:
在评论中,我看了一下Binance API。您使用的API端点是:
GET /api/v3/ticker/price
要从中获取信息,您需要向
发出HTTP请求:https://api.binance.com/api/v3/ticker/price
下面是示例代码:
import requests
import json
## Send a GET request to binance api
## Since this is a get request no apikey / secret is needed
response = requests.get("https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT")
## Print the text from the get request
## Output: {"symbol":"BTCUSDT","price":"37211.17000000"}
print(response.text)
## Response.text is a string so we can use json.loads on it
ticket = json.loads(response.text)
## Now that ticket is a python dict of the json string
## response from binance we can print what you want
print(f'$BTC @ {ticket["price"]}')
## Output: $BTC @ 37221.87000000