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

Cannot open a json file I am creating inside a function

I am trying to obtain a json file from this function, that is filled with items from the data variable. This variable data should then be dumped into the "hero_stats.json" file and I ought to open it for visualizing in the end. What is going wrong here? I can see all variables and names matching each others, am I missing some kind of call to open the file?

import pandas as pd, requests, json


# get updated info on game heroes

def get_hero_stats():
    data = requests.get("https://api.opendota.com/api/heroStats").json()
    pd.DataFrame(data).to_json("hero_stats.json")
    with open('hero_stats.json', 'w') as outfile:
        json.dump(data, outfile)


get_hero_stats()

I get no errors from this, just a message in the end with

Process finished with exit code 0

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

>Solution :

The function is returning None. You need to explicitly return a value, and assign it to something if you want to use it later.

import pandas as pd
import requests


# get updated info on game heroes

def get_hero_stats():
    data = requests.get("https://api.opendota.com/api/heroStats").json()
    pd.DataFrame(data).to_json("hero_stats.json")
    return data

data = get_hero_stats()
# Do stuff with data

Also there is no need to write the data twice, so I removed the second write operation…

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