打印包含USDT的对象
我想只打印出包含USDT的对象,来自:
requestT = requests.get('https://api1.binance.com/api/v3/ticker/price')
json_data = json.loads(requestT.text)
print(json_data)
举个例子:
data = [{'symbol': 'BNBETH', 'price': '0.16540000'}, {'symbol': 'BTCUSDT', 'price': '64321.11000000'}, {'symbol': 'ETHUSDT', 'price': '3330.76000000'}]
结果:
data1 = [{'symbol': 'BTCUSDT', 'price': '64321.11000000'}, {'symbol': 'ETHUSDT', 'price': '3330.76000000'}]
3 个回答
0
根据你想要的结果,我写了一个比较简单的解决方案。在这个方案中,我创建了一个新的列表,把匹配的内容放在里面。在代码中,我也对各个步骤进行了注释,以便更好地理解。显然,有很多方法可以得到相同的结果,这种方法是最基本的。
代码文件:Code.py
import json
data = [{'symbol': 'BNBETH', 'price': '0.16540000'}, {'symbol': 'BTCUSDT', 'price': '64321.11000000'}, {'symbol': 'ETHUSDT', 'price': '3330.76000000'}]
new_data = []
for usdt in data:
# here you check if "USDT" is inside the "symbol" key of each result
if 'USDT' in usdt['symbol']:
# if it exists, I insert every single match into the new list
new_data.append(usdt)
# I call the output with indent=4 for better reading
print(json.dumps(new_data, indent=4))
结果:
[
{
"symbol": "BTCUSDT",
"price": "64321.11000000"
},
{
"symbol": "ETHUSDT",
"price": "3330.76000000"
}
]
希望我能帮到你。
1
在尝试处理响应之前,务必要确认你的HTTP请求成功了。
你可以用一个简短的函数来处理这个,但我更喜欢用一个单独的函数。
所以……
import requests
def usdt(d):
return "USDT" in d.get("symbol", "")
with requests.get("https://api1.binance.com/api/v3/ticker/price") as response:
response.raise_for_status()
result = list(filter(usdt, response.json()))
print(result)
2
你可以用列表推导式来过滤数据,比如这样:
import requests
json_data = requests.get("https://api1.binance.com/api/v3/ticker/price").json()
usdt_data = [d for d in json_data if "USDT" in d["symbol"]]
print(*usdt_data, sep="\n")
输出结果是:
...
{'symbol': 'PDAUSDT', 'price': '0.12620000'}
{'symbol': 'AXLUSDT', 'price': '1.88250000'}
{'symbol': 'WIFUSDT', 'price': '2.26590000'}
{'symbol': 'METISUSDT', 'price': '97.19000000'}
{'symbol': 'AEVOUSDT', 'price': '2.39000000'}
{'symbol': 'BOMEUSDT', 'price': '0.01351400'}
{'symbol': 'ETHFIUSDT', 'price': '4.02700000'}