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


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


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}}

Leave a Reply