簡體   English   中英

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

[英]Using Json.dump and Json.load in Python

我在一個存儲用戶名並在調用時返回它們的程序中使用了兩個 json 函數 load 和 dump 。 下面是我的代碼:

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

您不能dump()兩個單獨的 json 對象到一個文件,然后load()它們。 load()期望文件中有一個 json 對象。

這對我有用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM