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

python, How to find specific key value in json file then save whole line of json file?

I am a newbie and I need to export specific key value in json file,I searched a lot of sites but couldn’t find the code I need, hope this helps me

my json file


{"person":{"name":"Silva","sex":"female","age":21}}
{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"Oliveira","sex":"female","age":35}}
{"person":{"name":"KENN","sex":"male","age":26}}

Need to export whole line json file where ‘sex’ is ‘male’ in JSON file

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

{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"KENN","sex":"male","age":26}}

full code required

>Solution :

Bearing in mind that the input file is not a JSON file per se. Each line is valid JSON and therefore has to be dealt with separately.

For example:

import json

with open ('foonew.txt', 'w', encoding='utf-8') as out:
    with open('foo.txt', encoding='utf-8') as j:
        for line in j:
            if (d := json.loads(line))['person']['sex'] == 'male':
                print(json.dumps(d), file=out)

The output file will look like:

{"person": {"name": "LANA", "sex": "male", "age": 28}}
{"person": {"name": "KENN", "sex": "male", "age": 26}}
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