简体   繁体   English

将字典转换为Json并追加到文件

[英]Converting dictionary as Json and append to a file

Scenario is i need to convert dictionary object as json and write to a file . 场景是我需要将字典对象转换为json并写入文件。 New Dictionary objects would be sent on every write_to_file() method call and i have to append Json to the file .Following is the code 新的Dictionary对象将在每次write_to_file()方法调用时发送,并且我必须将Json附加到文件中。以下是代码

def write_to_file(self, dict=None):
        f = open("/Users/xyz/Desktop/file.json", "w+")
        if json.load(f)!= None:
            data = json.load(f)
            data.update(dict)
            f = open("/Users/xyz/Desktop/file.json", "w+")
            f.write(json.dumps(data))
        else:

            f = open("/Users/xyz/Desktop/file.json", "w+")
            f.write(json.dumps(dict)

Getting this error "No JSON object could be decoded" and Json is not written to the file. 收到此错误“无法解码JSON对象”,并且Json未写入文件。 Can anyone help ? 有人可以帮忙吗?

this looks overcomplex and highly buggy. 这看起来过于复杂且高度错误。 Opening the file several times, in w+ mode, and reading it twice won't get you nowhere but will create an empty file that json won't be able to read. w+模式下多次打开文件,并读取两次不会无所适从,但会创建一个json无法读取的空文件。

  • I would test if the file exists, if so I'm reading it (else create an empty dict). 我会测试文件是否存在,如果有的话,我正在读取文件(否则创建一个空字典)。
  • this default None argument makes no sense. 这个默认的None参数毫无意义。 You have to pass a dictionary or the update method won't work. 您必须通过字典,否则update方法将无效。 Well, we can skip the update if the object is "falsy". 好吧,如果对象“虚假”,我们可以跳过更新。
  • don't use dict as a variable name 不要使用dict作为变量名
  • in the end, overwrite the file with a new version of your data ( w+ and r+ should be reserved to fixed size/binary files, not text/json/xml files) 最后,用新版本的数据覆盖文件( w+r+应该保留为固定大小/二进制文件,而不是text / json / xml文件)

Like this: 像这样:

def write_to_file(self, new_data=None):
     # define filename to avoid copy/paste
     filename = "/Users/xyz/Desktop/file.json"

     data = {}  # in case the file doesn't exist yet
     if os.path.exists(filename):
        with open(filename) as f:
           data = json.load(f)

     # update data with new_data if non-None/empty
     if new_data:
        data.update(new_data)

     # write the updated dictionary, create file if
     # didn't exist
     with open(filename,"w") as f:
         json.dump(data,f)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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