Python:使用变量/动态名称保存 JSON 响应?

发布于 2025-01-11 18:40:57 字数 508 浏览 0 评论 0原文

我对 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 am pretty new to Python and I am wondering how I can save a JSON response in a loop and change naming according to API request?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我不是你的备胎 2025-01-18 18:40:57

只需打开一个名为 {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))

Just open a file with name {i}.json and dump the json result in it:

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))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文