Python:正在使用 variable/dynamic 名称保存 JSON 响应?
Python: Saving JSON response with variable/dynamic name?
我是 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?
只需打开名称为 {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))
我是 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?
只需打开名称为 {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))