KAM_00
KAM_00

Reputation: 51

extract data from a json file in python

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?

Upvotes: 5

Views: 15630

Answers (5)

michelek
michelek

Reputation: 2546

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/

Upvotes: 3

Menglong Li
Menglong Li

Reputation: 2255

I'd rather like to provide a common method handling this case, the until method which is based on python functional programming, using this, you can find your target(provide a default value if not found), and you can decouple your filter criteria and candidates easily.

json_str = """
{"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"
      }]}}
"""

load the data to a python dict object

import json
data = json.loads(json_str)

Now here's the until part:

def until(terminate, iterator, default=None):
    try:
        i = next(iterator)
        if terminate(i):
            return i
        return until(terminate, iterator, default)
    except StopIteration:
        return default


ssn_target = '1234'

target_kid = until(lambda kid: ssn_target in kid['ssn'], iter(data['family']['kids']))

if target_kid is not None:
    print(target_kid['name'])
else:
    print('Opps! not found')

Note that:

Python has a rather small limit to how many recursive calls can be made (typically ~1000), so the iterable list shouldn't be tooo long.

Upvotes: 0

iways
iways

Reputation: 11

say you load your json text into js variable. kn = next((sj['name'] for sj in js['family']['kids'] if ('1234' in sj['ssn'])), None)

kn will give you the name if criteria found, otherwise it will be None. And of course you can change the condition into variable. Hope it helps.

Upvotes: 0

Rome
Rome

Reputation: 603

use json package like below

ans =     '{"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"
      }]}}'
temp = json.loads(ans)
for kid in  temp['family']['kids']:
     print kid['name'],kid['ssn']

hope this is what you look for .

Upvotes: 0

akash karothiya
akash karothiya

Reputation: 5950

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'

Upvotes: 2

Related Questions