I have a code that finds a fixed value,But i need a code to check if a JSON file key contains a specific value, how should i modify it,I am a newbie and I am learning it
my code
import json
with open ('G:\\1.json', 'w', encoding='utf-8') as out:
with open('G:\\1.json', encoding='utf-8') as j:
for line in j:
if (d := json.loads(line))['_source']['sex'] == 'female':
print(json.dumps(d), file=out)
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":32}}
I want the output,"age" contains "2"
{"person":{"name":"Silva","sex":"female","age":21}}
{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"KENN","sex":"male","age":32}}
CodePudding user response:
If you want to check if a number contains a digit, convert it to a string.
d = json.loads(line)
age_string = str(d['_source']['age'])
if "2" in age_string:
print(json.dumps(d), file=out)
