Search code examples
pythonjsonloopssave

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

  • 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))