【问题标题】:How to write each JSON objects in a newline of JSON file? (Python)如何在 JSON 文件的换行符中写入每个 JSON 对象? (Python)
【发布时间】:2018-06-04 08:45:59
【问题描述】:

我遇到了一个问题,确实我有一个 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()

【问题讨论】:

  • 你会得到什么样的错误,因为如果你有一个像上面描述的文件,你就没有有效的 json。它应该有 [{},{}] 作为符号,然后你有一个有效的 json 文件要加载。
  • 对不起,这只是一个例子。我没有任何错误。结果与我的预期不符。也许我发现了,在分隔符中我会放 '\n'。我会试试的。
  • \n 确实是换行符。如果你使用windows你应该使用\r\n,Unix系统通常只需要\n
  • @RonNabuurs 我使用 Windows,对于文本文件我写 \r\n 作为换行符,但对于 JSON 文件 \n 似乎足够了。 (用记事本++打开)。

标签: python json


【解决方案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)+"]")

【讨论】:

    【解决方案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)
    

    【讨论】:

    • 我的回答有什么问题? 20 MB 文件没有任何问题。另外,我写了一个 JSON 文件作为输出。
    • @huseyin39 你的代码没有问题,但对我来说,使用.replace('"},', '"},\n') 似乎要容易得多
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多