extract data from a json file in python

Viewed 14980

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?

5 Answers

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'

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 .

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.

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.

Related