Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Saving JSON response with variable/dynamic name?

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading