您好,首先我要了解如何从JSON过滤python词典中的信息,然后再将其写入JSON文件中。我采用常规工作流程,但我离开的地方是我们并不总是确切知道我们必须反复说明一个简单但真实的示例。
为此,我使用CoinMarketCap的缩写,这是数据结构:
{
"data": {
"1": {
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"website_slug": "bitcoin",
"rank": 1,
"circulating_supply": 17168112.0,
"total_supply": 17168112.0,
"max_supply": 21000000.0,
"quotes": {
"USD": {
"price": 8159.91,
"volume_24h": 6805930000.0,
"market_cap": 140090248790.0,
"percent_change_1h": -0.65,
"percent_change_24h": 5.84,
"percent_change_7d": 18.14
}
},
"last_updated": 1532445803
},
"1027": {
"id": 1027,
"name": "Ethereum",
"symbol": "ETH",
"website_slug": "ethereum",
"rank": 2,
"circulating_supply": 100891486.0,
"total_supply": 100891486.0,
"max_supply": null,
"quotes": {
"USD": {
"price": 472.418,
"volume_24h": 2187530000.0,
"market_cap": 47662953974.0,
"percent_change_1h": -1.42,
"percent_change_24h": 2.14,
"percent_change_7d": -1.83
}
},
"last_updated": 1532445813
},
"52": {
"id": 52,
"name": "XRP",
"symbol": "XRP",
"website_slug": "ripple",
"rank": 3,
"circulating_supply": 39315683476.0,
"total_supply": 99991900487.0,
"max_supply": 100000000000.0,
"quotes": {
"USD": {
"price": 0.458599,
"volume_24h": 305718000.0,
"market_cap": 18030133126.0,
"percent_change_1h": -1.22,
"percent_change_24h": 1.69,
"percent_change_7d": -5.25
}
},
"last_updated": 1532445797
},
"metadata": {
"timestamp": 1532445415,
"num_cryptocurrencies": 1664,
"error": null
}
}
您会看到嵌套的字典,并且有一个地方您无法显式地进行迭代,我们必须动态地进行迭代,否则我们应该知道加密货币的ID。
我们开始探索字典:
#!/usr/bin/python3
import json
import requests
response = requests.get("https://api.coinmarketcap.com/v2/ticker/")
data = json.loads(response.text)
def keep(data):
for i in data['data'].key():
print(i)
keep(data)
如您所见,这是要迭代的复杂部分。
我设法摆脱了复杂的部分,从而获得了十大加密货币:
#!/usr/bin/python3
import json
import requests
response = requests.get("https://api.coinmarketcap.com/v2/ticker/")
data = json.loads(response.text)
def keep(data):
for i in data['data'].values():
if i['rank'] <= 10:
print(json.dumps(i, indent=4))
keep(data)
但是我不能将其写到JSON文件中,希望您能对我有所帮助。
答案 0 :(得分:0)
这就是您想要做的:
import json
import requests
response = requests.get("https://api.coinmarketcap.com/v2/ticker/")
data = json.loads(response.text)
finallist=[]
def keep(data):
for i in data['data'].values():
if i['rank'] <= 10:
finallist.append(i)
keep(data)
#jsondata = json.dumps(finallist)
with open('data1sk.json', 'w') as outfile:
json.dump(finallist, outfile)
这应该可以达到您想要的结果,但是您没有告诉您,什么显然不适用于您的情况。但是,这是您可以尝试的解决方案。