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

2024-06-26 12:38:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

然后,我想用同样的方法将对象写回文件中(1个对象=1行)。在

我试过用“缩进”和“分隔符”来实现,但它不起作用。在

我想要:

^{pr2}$

谢谢你的阅读。在

    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()

Tags: 文件对象方法json元素data属性分隔符
2条回答

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

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

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

相关问题 更多 >