简体   繁体   English

我的程序有时会在json文件中的数据末尾写一个额外的]或}?

[英]My program sometimes writes an extra ] or } at the end of data in json file?

I have written a note taking tool for myself as my first program. 我为自己写了一个笔记工具作为我的第一个程序。 Its actually working really well for the most part however sometimes the program will write an extra ] or } at the end of the list or dict stored inside of said json file. 它实际上在大多数情况下工作得很好,但有时程序会在list末尾写一个额外的]}或存储在所述json文件中的dict

It doesn't happen often and I think it is only happening when I am writing new lines of code or changing existing lines that read/write to said files. 它并不经常发生,我认为只有当我编写新的代码行或更改读取/写入所述文件的现有行时才会发生这种情况。 I am not 100% sure but that is what it looks like. 我不是100%肯定,但这就是它的样子。

For example I have a single list stored in a file and I use the indent="" flag to make sure as it writes the files its a little more readable for me if I ever have to edit said files. 例如,我有一个存储在文件中的单个list ,并且我使用indent=""标志来确保在写入文件时,如果我必须编辑所述文件,它对我来说更具可读性。 Sometimes when running my program after changing up some code or adding code I get an error stating a file has "extra data" in it. 有时在更改某些代码或添加代码后运行我的程序时,我收到一条错误,指出文件中有“额外数据”。 The error looks something like this: 错误看起来像这样:

    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 6 column 2 (char 5791)

and the cause of the error would be something like this: 并且错误的原因将是这样的:

[
"Help",
"DataTypes",
"test",
"Variables",
]] # the error would be cause by this extra ] at the end of the list

What I don't understand is why does the program sometimes add and extra ] or } at the end of the data in my json files? 我不明白为什么程序有时会在我的json文件中的数据末尾添加和添加]或}?

Is there something I am doing wrong when I open the file or dump to the file? 当我打开文件或转储到文件时,我有什么问题吗?

Here are some sections of code I have that are used to open files and dump to files: 以下是我用于打开文件和转储到文件的代码的一些部分:

path = "./NotesKeys/"
notebook = dict()
currentWorkingLib = ""
currentWorkingKeys = ""
#~~~~~~~~~~~~~~~~~~~< USE TO open all files in Directory >~~~~~~~~~~~~~~~~~~~
with open("%s%s"%(path,"list_of_all_filenames"), "r") as listall:
    list_of_all_filenames = json.load(listall)

def openAllFiles(event=None):
    global path
    for filename in os.listdir(path):
        with open(path+filename, "r+") as f:
            notebook[filename] = json.load(f)
openAllFiles()

And here is how I am updating the data in the file. 这是我如何更新文件中的数据。 Just ignore the e1Current, e1allcase, e2Current they are used to keep the format of the users input for filenames (dict key) lower case in the dictionaries where the notes are stored and maintain the case the user imputed for a display list. 只需忽略e1Current, e1allcase, e2Current它们用于保存用户输入文件名(dict键)的小写字母在存储笔记的字典中的小写,并维护用户为显示列表估算的情况。 This should not be related to the file read write issue.: 这不应该与文件读写问题有关:

Edit: removed unrelated code per commenters request. 编辑:删除每个评论者请求的不相关代码。

#~~~~~~~~~~~~~~~~~~~< UPDATE selected_notes! >~~~~~~~~~~~~~~~~~~~

            dict_to_be_updated = notebook[currentWorkingLib]
            dict_to_be_updated[e1Current] = e2Current
            with open("%s%s"%(path,currentWorkingLib),"r+") as working_temp_var:
                json.dump(dict_to_be_updated, working_temp_var, indent = "")

I am aware of how to open a file and use the data and how to dump data to said file and update the content loaded in the variables of the program based off the newly dumped data. 我知道如何打开文件并使用数据以及如何将数据转储到所述文件,并根据新转储的数据更新程序变量中加载的内容。

Am I missing something important during this process? 我在这个过程中遗漏了哪些重要内容? Should I be doing something to ensure data integrity in the json files? 我应该做些什么来确保json文件中的数据完整性吗?

You are opening files in read-write mode, r+ : 您正在以读写模式打开文件, r+

with open("%s%s"%(path,currentWorkingLib),"r+") as working_temp_var:

This means you'll be writing to a file that already has data in it , and sometimes the existing data is longer than what you are now writing to the file. 这意味着您将写入已包含数据的文件,有时现有数据比您现在写入文件的数据 That means you'll end up with some trailing data at the end. 这意味着你最终会得到一些尾随数据。

You can see this by writing a shorter demo string to a file, then using r+ to write less data to the same file, then reading again: 您可以通过将较短的演示字符串写入文件,然后使用r+较少的数据写入同一文件,然后再次读取来查看:

>>> with open('/tmp/demo', 'w') as init:
...     init.write('The quick brown fox jumps over the lazy dog\n')
...
44
>>> with open('/tmp/demo', 'r+') as readwrite:
...     readwrite.write("Monty Python's flying circus\n")
...
29
>>> with open('/tmp/demo', 'r') as result:
...     print(result.read())
...
Monty Python's flying circus
r the lazy dog

Don't do this. 不要这样做。 Use w write mode so the file is truncated first: 使用w写入模式,以便首先截断文件:

with open("%s%s"%(path,currentWorkingLib), "w") as working_temp_var:

This ensures your file is cut back to size 0 before you write a new JSON document. 这可确保在编写新的JSON文档之前将文件缩减为0。

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

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