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

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

Leave a Reply