5

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?

1
  • depends on the file size, dict keys are dynamically changed or not .etc; simply json.loads to get the dict and go on comparing later on? Or could you please paste your code snippet here? Commented Nov 15, 2017 at 7:57

5 Answers 5

3

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/

Sign up to request clarification or add additional context in comments.

Comments

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'

1 Comment

This way worked perfect, how would I do it if i had multiple kids with "1234" and wanted the list of names with the sex?
0

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 .

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.