extract data from a json file in python
14,484
Solution 1
Actually question was about extracting from file
So here you are:
import json
with open('data.json') as json_file:
data = json.load(json_file)
for kid in data['family']['kids']:
if '1234' in kid['ssn']:
print(kid['name'])
Additional reading: https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/
Solution 2
You can first iterate kids and apply condition
import json
js = '''your json text data'''
j = json.loads(js)
for items in j['family']['kids']:
if '1234' in items['ssn']:
print(items['name'])
Output
'jim'
Related videos on Youtube
Author by
KAM_00
Updated on September 15, 2022Comments
-
KAM_00 over 1 year
I have been try to find the best way to search a particular value and extract the data. I am new and hope i have worded this correctly.
{"family": { "name": "Mary", "age": "32", "sex": "female", "kids": [ { "name": "jim", "age": "10", "sex": "male", "dob_year": "2007", "ssn": "123-23-1234" }, { "name": "jill", "age": "6", "sex": "female", "dob_year": "2011", "ssn": "123-23-1235" }]}}
if i needed to search "ssn" containing "1234" and return the "name" "jim" what would be the best way to go about achieving this?
-
KAM_00 over 6 yearsThis way worked perfect, how would I do it if i had multiple kids with "1234" and wanted the list of names with the sex?