如何在JSON文件的新行中编写每个JSON对象?(Python)

时间:2021-06-14 15:28:13

I am stuck with a problem, indeed I have a JSON file in which each objects is in a line. So, if there are 100 objects, there will be 100 lines.

我遇到了一个问题,实际上我有一个JSON文件,其中每个对象都在一行中。如果有100个对象,就会有100行。

[{ "attribute1" : "no1", "attribute1": "no2"}
{ "attribute1" : "no12", "attribute1": "no22"}]

I open this JSON file, and delete some atttributes of every elements.

我打开这个JSON文件,删除每个元素的一些附加项。

Then, I want to write the objects back into the file in the same way (1 object = 1 line).

然后,我想以同样的方式将对象写回文件(1 object = 1行)。

I have tried to do so with "indent" and "separators" but it does not work.

我曾尝试用“缩进”和“分隔符”来实现这一点,但它不起作用。

I would like to have :

我想要:

[{ "attribute1": "no2"}
{"attribute1": "no22"}]

Thanks for reading.

感谢你的阅读。

    with open('verbes_lowercase.json','r+',encoding='utf-8-sig') as json_data:
        data=json.load(json_data)
        for k in range(len(data)):
            del data[k]["attribute1"]
        json.dump(data,json_data,ensure_ascii=False , indent='1', separators=(',',':'))
        json_data.seek(0)
        json_data.truncate()

2 个解决方案

#1


1  

I use a trick to do what I want, to rewrite all the objects into a new line. I write what I want to keep into a newfile.

我用一个技巧来做我想做的事,把所有的对象重写成一条新的线。我把我想保存的东西写进一个新文件里。

with open('verbes_lowercase.json','r',encoding='utf-8-sig') as json_data:
    data=json.load(json_data)
    with open("verbes.json",'w',encoding="utf-8-sig") as file:
        file.write("[")
        length=len(data)
        for k in range(0,length):
            del data[k]["attribute1"]
            if (k!=length-1):
                 file.write(json.dumps(data[k], ensure_ascii=False)+",\n")
            else:
                file.write(json.dumps(data[length-1], ensure_ascii=False)+"]")

#2


0  

As I mentioned in the code if you want to work with big files of json you would have to find an another way

正如我在代码中提到的,如果您想处理json的大文件,您必须找到另一种方法

import json


def write(file_object, dictionary_object):
    file_object.write(json.dumps(dictionary_object).replace('"},', '"},\n'))


def safe_write(file_object, dictionary_object):
    file_object.truncate(0)
    file_object.write(json.dumps(dictionary_object).replace('"},', '"},\n'))


# Easy But Bad For Big Json Files
dict_object = [{"attribute1": "no1", "attribute12": "no2"}, {"attribute1": "no12", "attribute12": "no22"}, {"attribute1": "no13", "attribute12": "no23"}, {"attribute1": "no14", "attribute12": "no24"}]
with open('json_dump.txt', 'w') as f:
    write(f, dict_object)  # Writes Perfectly
    dict_object.append({"attribute1": "no15", "attribute12": "no25"})
    safe_write(f, dict_object)  # Writes Perfectly (We used the safe_write function to avoid appending to the end of the file) (Actually we can seek to the file's start but if you removed a element from list this makes the file shorter and the start of the file will be written out but the end of the file will still remain)

#1


1  

I use a trick to do what I want, to rewrite all the objects into a new line. I write what I want to keep into a newfile.

我用一个技巧来做我想做的事,把所有的对象重写成一条新的线。我把我想保存的东西写进一个新文件里。

with open('verbes_lowercase.json','r',encoding='utf-8-sig') as json_data:
    data=json.load(json_data)
    with open("verbes.json",'w',encoding="utf-8-sig") as file:
        file.write("[")
        length=len(data)
        for k in range(0,length):
            del data[k]["attribute1"]
            if (k!=length-1):
                 file.write(json.dumps(data[k], ensure_ascii=False)+",\n")
            else:
                file.write(json.dumps(data[length-1], ensure_ascii=False)+"]")

#2


0  

As I mentioned in the code if you want to work with big files of json you would have to find an another way

正如我在代码中提到的,如果您想处理json的大文件,您必须找到另一种方法

import json


def write(file_object, dictionary_object):
    file_object.write(json.dumps(dictionary_object).replace('"},', '"},\n'))


def safe_write(file_object, dictionary_object):
    file_object.truncate(0)
    file_object.write(json.dumps(dictionary_object).replace('"},', '"},\n'))


# Easy But Bad For Big Json Files
dict_object = [{"attribute1": "no1", "attribute12": "no2"}, {"attribute1": "no12", "attribute12": "no22"}, {"attribute1": "no13", "attribute12": "no23"}, {"attribute1": "no14", "attribute12": "no24"}]
with open('json_dump.txt', 'w') as f:
    write(f, dict_object)  # Writes Perfectly
    dict_object.append({"attribute1": "no15", "attribute12": "no25"})
    safe_write(f, dict_object)  # Writes Perfectly (We used the safe_write function to avoid appending to the end of the file) (Actually we can seek to the file's start but if you removed a element from list this makes the file shorter and the start of the file will be written out but the end of the file will still remain)