Home > Back-end >  Remove lines from jsonfile in python
Remove lines from jsonfile in python

Time:12-19

Here my problem I got a json file that containe empty obj i would like to remove them from this json file and save it in a new json file.

Here my json exemple called 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": []
        }
    },
    {},
    {},
]

What I've tried to do:

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

CodePudding user response:

First of all, that is not a valid JSON, so after fixing it and making it valid JSON, you can do this way to filter empty dictionaries from the list.

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)

Full Code:

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