如何将Python 3.4输入信息导出到JSON?

时间:2014-12-07 02:46:52

标签: python json save

我正在尝试构建一个能够跟踪信息和其他内容的人工智能程序,但是在尝试将信息导出到文件时遇到了问题。我是Python的新手,想要帮助确定可能存在的问题。

这是源代码。

#Importations
import jsonpickle
import math
import os
import sys
import time
from random import randrange, uniform
#Setups
SAVEGAME_FILENAME = 'aisetup.json'
game_state = dict()
#Program AI
class Computer(object):
    def __init__(self, name, creator):
        self.name = name
        self.creator = creator
#User Information
class Human(object):
    def __init__(self, name, birth):
        self.name = name
        self.birth = birth       
#Load Program Save
def load_game():
    """Load game state from a predefined savegame location and return the
    game state contained in that savegame.
    """
    with open(SAVEGAME_FILENAME, 'r') as savegame:
        state = jsonpickle.decode(savegame.read())
    return state
#Save Program to JSON
def save_game():
    """Save the current game state to a savegame in a predefined location.
    """
    global game_state
    with open(SAVEGAME_FILENAME, 'w') as savegame:
        savegame.write(jsonpickle.encode(game_state))
#Initialize Program
def initialize_game():
    """Runs if no AISave is found"""
    UserProg = Human('User', '0/0/0')
    AISystem = Computer('TempAI', 'Austin Hargis')

    state = dict()
    state['UserProg'] = [UserProg]
    state['AISystem'] = [AISystem]
    return state
#TextPad
#Main Code - Runs Multiple Times per Being Openned
def prog_loop():
    global game_state
    name = input (str("What is your name?: "))
    save_game()

#Main Program
def main():
    """Main function. Check if a savegame exists, and if so, load it. Otherwise
    initialize the game state with defaults. Finally, start the game.
    """
    global game_state

    if not os.path.isfile(SAVEGAME_FILENAME):
        game_state = initialize_game()
    else:
        game_state = load_game()
    prog_loop()
#Launch Code
if __name__ == '__main__':
    main()

每次运行时,它都会将信息导出到这样的文件中:

{"UserProg": [{"birth": "0/0/0", "py/object": "__main__.Human", "name": "User"}], "AISystem": [{"py/object": "__main__.Computer", "name": "TempAI", "creator": "Austin Hargis"}]}

我希望它将您的名字导出到该文件夹​​,但它无法正常工作。

1 个答案:

答案 0 :(得分:1)

您永远不会执行任何具有用户输入名称的内容:

def prog_loop():
    global game_state
    name = input (str("What is your name?: "))
    save_game()

name只是一个局部变量。如果您想将其保存为人类的名称,则需要在游戏状态的UserProg条目中进行设置:

def prog_loop():
    name = input("What is your name?: ")
    # game_state['UserProg'] is a list with one Human instance in it
    game_state['UserProg'][0].name = name
    save_game()

因为您正在改变 game_state中包含的可变对象而不是分配给game_state本身,所以您不需要global语句。 str()调用也是多余的,"..."语法已经生成了一个字符串,将其转换为字符串再次几乎没有意义。