从python中的json文件中删除行

Posted

技术标签:

【中文标题】从python中的json文件中删除行【英文标题】:Remove lines from jsonfile in python 【发布时间】:2022-01-21 02:23:25 【问题描述】:

我的问题是我有一个包含空 obj 的 json 文件,我想从这个 json 文件中删除它们并将其保存在一个新的 json 文件中。

这里我的 json 示例称为 db_origin.json :

[
    # Would like remove this
    #====================#
    ,
    ,
    ,
    ,
    ,
    #====================#
    
        "model": "auth.user",
        "pk": *,
        "fields": 
            "password": "*********",
            "last_login": "********",
            "is_superuser": true,
            "username": "******",
            "first_name": "",
            "last_name": "",
            "email": "",
            "is_staff": true,
            "is_active": true,
            "date_joined": "2016-12-08T11:04:07",
            "groups": [
                1
            ],
            "user_permissions": []
        
    ,
    ,
    ,
]

我尝试做的事情:

import json

def read_write():
    with open('db_origin.json') as json_file:
        lines = json_file.readlines()
        for line in lines:
            line.replace(('    ,\n'), "")

        with open('cleaned.json', 'w') as f:
            json.dump(lines, f, indent=4)
            

read_write()

【问题讨论】:

嗨!欢迎来到堆栈溢出!不幸的是,除非您发布您编写的代码,否则 SO 社区将无法提供帮助。我们不是邮购代码。 【参考方案1】:

首先,这不是一个有效的 JSON,所以在修复它并使其成为有效的 JSON 之后,您可以通过这种方式从列表中过滤空字典。

import json
json_str='''[,,,,,"model":"auth.user","pk":"*","fields":"password":"*********","last_login":"********","is_superuser":true,"username":"******","first_name":"","last_name":"","email":"","is_staff":true,"is_active":true,"date_joined":"2016-12-08T11:04:07","groups":[1],"user_permissions":[],,]'''
python_list = json.loads(json_str)
filtered_empty = list(filter(None, python_list))
print(filtered_empty)

完整代码:

import json

def read_write():
    with open('db_origin.json') as json_file:
        python_list = json.load(json_file)
        filtered_empty = list(filter(None, python_list))

    with open('cleaned.json', 'w') as f:
        json.dump(filtered_empty, f, indent=4)
            

read_write()

【讨论】:

以上是关于从python中的json文件中删除行的主要内容,如果未能解决你的问题,请参考以下文章