在Python中使用Json.dump和Json.load

时间:2017-03-04 18:14:37

标签: python json

我在一个存储用户名的程序中使用两个json函数加载和转储,并在调用时返回它们。以下是我的代码:

#Saving data for later use using json

import json
#Load the username, if it has been stored previously.
# Otherwise, prompt for the username and store it.
def get_stored_username():
    """Get stored username if available."""
    filename = 'username.json'
    try:
        with open(filename) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    """Prompt for a new username"""
    username = input("What is your name? ")
    filename = 'username.json'
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
    return username

def greet_user():
    """Greet the user by name"""
    username = get_stored_username()
    if username:
        correct = input("Are you " + username + "? (y/n) ")
        if correct == 'y':
            print("Welcome back, " + username + "!")
        else:
            username = get_new_username()
            print("We'll remember you when you come back, " + username + "!")
    else:
        username = get_new_username()
        print("We'll remember you when you come back, " + username + "!")

greet_user()

我运行了两次get_new_username()函数,并且运行正常。但是,一旦我运行greet_user()函数,我就会收到以下错误。有没有人遇到过这个,你做了什么来补救它?

Traceback (most recent call last):
  File "remember_me.py", line 39, in <module>
    greet_user()
  File "remember_me.py", line 27, in greet_user
    username = get_stored_username()
  File "remember_me.py", line 11, in get_stored_username
    username = json.load(f_obj)
  File "/usr/lib/python3.5/json/__init__.py", line 268, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.5/json/decoder.py", line 342, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 15 (char 14)

2 个答案:

答案 0 :(得分:0)

你不能dump()两个单独的json对象到一个文件,然后load()它们。 load()期望文件中有一个json对象。

答案 1 :(得分:0)

这对我有用:

import json

def get_stored_username():
    """Get stored username if available."""
    filename = 'username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    """Prompt for a new username."""
    username = input("What is your name? ")
    filename = 'username.json'
    with open(filename, 'w') as f:
        json.dump(username, f)
    return username

def greet_user():
    """Greet the user by name."""
    username = get_stored_username()
    if username:
        print("Welcome back " + username)
    else:
        username = get_new_username()
        print(f"We'll remember you when you come back, " + username)

greet_user()