json 文件未被 python 编辑

json file does not get edited by python

我想将我的 API 监听器的 return 放入 json 文件。 不幸的是,当我 运行 下面的代码只有空字典被打印到 json 文件中。 我不明白为什么,有谁知道为什么会这样吗?

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)

正如所写,您(无用地)在全局范围内而不是在函数范围内声明名称 game global。

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)

但是,如果您要用新值 return 完全覆盖 game 的值,则无需game 全球第一。

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)