我對 Python 很陌生,我想知道如何在回圈中保存 JSON 回應并根據 API 請求更改命名?
TestList = ["bitcoin", "avalanche", "ethereum"]
TestListLen = len(TestList)
for i in TestList:
# Request JSON response
r = requests.get (f"https://api.coingecko.com/api/v3/coins/{i}/market_chart?vs_currency=usd&days=max&interval=daily")
if r.status_code >= 201:
continue
data = r.json()
# How to save that response as eg. bitcoin.json or ethereum.json according to the names in TestList?
uj5u.com熱心網友回復:
只需打開一個帶有名稱的檔案{i}.json并將 json 結果轉儲到其中:
import requests
import json
TestList = ["bitcoin", "avalanche", "ethereum"]
for i in TestList:
r = requests.get (f"https://api.coingecko.com/api/v3/coins/{i}/market_chart?vs_currency=usd&days=max&interval=daily")
if r.status_code >= 201:
continue
data = r.json()
with open(f'{i}.json', 'w') as fd: # add these two lines
fd.write(json.dumps(data))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/437369.html
