python怎么读取有多个值的json文件报错
username.json文件只有一个值使用json.load()程序可以正常运行,但是username.json有多个值就报错报错信息:
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 15 (char 14)
源码:
import json
def my_greet_user():
filename = 'username.json'
try:
input_name = input('你叫什么名字!\n')
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
print('新用户你好!欢迎你加入我们')
username = input_name
with open(filename,'w') as f:
json.dump(username,f)
print('你提供的名字已记录!')
else:
if input_name != username:
with open(filename, 'w') as f:
json.dump(input_name, f)
print('你好'+input_name+'!')
print('你已经成为我们的一员!')
else:
print(input_name+'你好!欢迎你回来!')
my_greet_user() json文件不发一下看看吗 kogawananari 发表于 2020-9-12 00:58
json文件不发一下看看吗
json文件就是写入的用户名
"\u675c\u752b""\u675c\u752b" 淡淡凉 发表于 2020-9-12 13:46
json文件就是写入的用户名
"%u675c%u752b""%u675c%u752b"
用列表存不好吗 kogawananari 发表于 2020-9-12 16:34
用列表存不好吗
用列表可以,没有报错了
def my_greet_user():
filename = 'username.json'
usernames = []
try:
input_name = input('你叫什么名字!\n')
with open(filename) as f:
usernames = json.load(f)
except FileNotFoundError:
print('新用户你好!欢迎你加入我们')
usernames.append(input_name)
with open(filename,'w') as f:
json.dump(usernames,f)
print('你提供的名字已记录!')
else:
if input_name not in usernames:
usernames.append(input_name)
with open(filename, 'w') as f:
json.dump(usernames, f)
print('你好'+input_name+'!')
print('你已经成为我们的一员!')
else:
print(input_name+'你好!欢迎你回来!')
页:
[1]