简体   繁体   中英

Using Json.dump and Json.load in Python

I am using the two json functions load and dump in a program that stores user names and returns them when called on. Below is my code:

#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()

I ran the get_new_username() function twice, and that worked fine. However, once I ran the greet_user() function, I get the following errors. Has anyone ever came across this, and what did you do to remedy it?

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)

You can't dump() two separate json objects to a file, then load() them. load() expects there to be one json object in the file.

This worked for me:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM