Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove lines from jsonfile in python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading