Lars H
Lars H

Reputation: 11

json file does not get edited by python

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)

Upvotes: 0

Views: 43

Answers (1)

chepner
chepner

Reputation: 531165

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)

Upvotes: 2

Related Questions