使用Python的json文件加载问题

时间:2017-04-29 06:48:37

标签: python json load

我尝试使用Python转储并将字典加载到json文件。我可以毫无问题地转储文件。但是,当我尝试将文件加载到临时字典时,会发生错误。我无法弄清楚这个问题,任何人都可以帮我解决这个问题吗?谢谢

import os
import json

def get_stored_birth():
    filename ='C:/Users/Sam/name.json'
    temp = {}

    with open(filename,'r+') as f_obj1:
        temp =json.load(f_obj1)
        print(temp.get(name),"is the birthday of",name)

def get_new_birth():
    birth=str(input())
    my_dict[name]=birth
    print("Birthday database updated")      
    filename ='C:/Users/Sam/name.json'
    with open(filename,'a') as f_obj:
            f_obj.write('\n')
            json.dump(my_dict,f_obj) 
    return name

my_dict={}

def quit():
   """This function quit program"""  
   return quit

while True:
    filename ='C:/Users/Sam/name.json'
    print("Enter a name:(blank to quit)")
    name= str(input())
    if name=="":              
        exit()

    if name in my_dict:
         name= get_stored_birth()
    else:
        print("I dont have info for",name)
        print("What is their birthday")
        name= get_new_birth()

回溯如下:

Traceback (most recent call last):


     File "C:\Users\Sam\Desktop\Tianxu_Assignment2\Assignment 2.py", line 45, in <module>
        name= get_stored_birth()
      File "C:\Users\Sam\Desktop\Tianxu_Assignment2\Assignment 2.py", line 10, in get_stored_birth
        temp =json.load(f_obj1)
      File "C:\Users\Sam\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 299, in load
        parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
      File "C:\Users\Sam\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 354, in loads
        return _default_decoder.decode(s)
      File "C:\Users\Sam\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 342, in decode
        raise JSONDecodeError("Extra data", s, end)
    json.decoder.JSONDecodeError: Extra data: line 3 column 1 (char 12)

2 个答案:

答案 0 :(得分:1)

问题解决了!!! 1.替换为open(文件名,'a')为f_obj,替换为open(文件名,'w') 2。     如果在my_dict中有名字:     不应该检查my_dict !!!每次启动程序都会使用新的“字典”。我动了 filename ='C:/Users/Sam/name.json'     temp = {}

with open(filename,'r+') as f_obj1:
    temp =json.load(f_obj1)

到主循环并检查temp中是否有名称:

谢谢你们!

答案 1 :(得分:0)

您正在将新json附加到您创建的先前jsons。只需替换这一行:
with open(filename,'a') as f_obj:
用这一个:
with open(filename,'w') as f_obj: