0

i want to put the return of my API listener to a json file. Unfortunately when i run the code below only the empty dictionary does get printed to the jsonfile. I don't see why, does anyone know why it is like that?

from chessdotcom import get_player_game_archives
import pprint
import requests
import pymongo
import json

uName = input()
printer = pprint.PrettyPrinter()
global game 
game = {}

def get_most_recent_game(username):
    data = get_player_game_archives(username).json
    url = data['archives'][-1]
    games = requests.get(url).json()
    game = games['games'][-1]
    printer.pprint(game)
    return(game)

get_most_recent_game(uName)

with open('Games.json', 'w') as json_file:
    json.dump(game, json_file)
2
  • Looks like you need game = get_most_recent_game(uName). Commented Aug 20, 2021 at 14:22
  • Also if you wanted get_most_recent_game to work with the global game object you would put global game inside the definition of get_most_recent_game. As it is, it's better to avoid global variables. I would just remove game as a global variable. Commented Aug 20, 2021 at 14:23

1 Answer 1

2

As written, you (uselessly) declare the name game global in the global scope, not in the function scope.

def get_most_recent_game(username):
    global game
    data = get_player_game_archives(username).json
    url = data['archives'][-1]
    games = requests.get(url).json()
    game = games['games'][-1]
    printer.pprint(game)
    return(game)

However, if you are going to completely overwrite the value of game with a new value and return it anyway, there's no need to make game global in the first place.

uName = input()
printer = pprint.PrettyPrinter()

def get_most_recent_game(username):
    data = get_player_game_archives(username).json
    url = data['archives'][-1]
    games = requests.get(url).json()
    game = games['games'][-1]
    printer.pprint(game)
    return game 

game = get_most_recent_game(uName)

with open('Games.json', 'w') as json_file:
    json.dump(game, json_file)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.