How to extract elements from JSON File with python?

I have the JSON file below and i am trying to extract the value dob_year from each item if the name element is jim.

This is my try:

import json

with open('j.json') as json_file:
    data = json.load(json_file)
    if data['name'] == 'jim'
        print(data['dob_year'])

Error:

File "extractjson.py", line 6 if data['name'] == 'jim' ^ SyntaxError: invalid syntax

this is my file.

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

4 answers

  • answered 2020-02-16 15:04 Yann

    You need to iterate over the list in the JSON file

    data = json.load(json_file)
    for item in data:
        if item['name'] == 'jim':
            print(item['dob_year'])
    

  • answered 2020-02-16 15:04 Raphael

    data is a list of dictionaries! you cannot directly access the key value pairs. Try encapsulating it in a loop to check every dict in the list:

    import json
    
    with open('j.json') as json_file:
        data = json.load(json_file)
        for set in data:
            if set['name'] == 'jim':
                print(set['dob_year'])
    

  • answered 2020-02-16 15:20 gp42

    I suggest to use list comprehension:

    import json
    
    with open('j.json') as json_file:
        data = json.load(json_file)
    
    print([item["dob_year"] for item in a if item["name"] == "jim"])
    

  • answered 2020-02-16 15:28 Aamir Syed

    json.load()
    

    returns a list of entries, the way you have saved it. You have to iterate through all list items, then search for your field in the list item. Also, if it is a repetitive task, make a function out of it. You can pass different files, fields to be extracted, etc. this way, and it can make your job easier.

    Example:

    def extract_info(search_field, extract_field, name, filename):
    
    import json
    
    with open(filename) as json_file:
        data = json.load(json_file)
        for item in data:
            if item[search_field] == name:
                print(item[extract_field])
    
    extract_info('name','dob_year','jim','j.json')