如何在JSON文件的换行符中编写每个JSON对象? (蟒蛇)

时间:2018-06-04 08:46:00

标签: python json

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

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

我打开这个JSON文件,并删除每个元素的一些属性。

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

我试图用"缩进"和"分隔符"但它不起作用。

我想:

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

感谢阅读。

    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 个答案:

答案 0 :(得分:1)

我使用技巧来做我想要的,将所有对象重写为新行。我把我要保留的内容写入新文件中。

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)+"]")

答案 1 :(得分:0)

正如我在代码中提到的,如果你想使用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)