0

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"
      }
    ]
1
  • Your data is a list of dictionaries. You need to loop through (d['dob_year'] for d in data if d['name'] == 'jim') Commented Feb 16, 2020 at 15:05

4 Answers 4

2

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'])
Sign up to request clarification or add additional context in comments.

1 Comment

i am getting the error: File "extractjson.py", line 6 if data['name'] == 'jim' ^ SyntaxError: invalid syntax
0

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"])

Comments

0
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')

Comments

0

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'])

2 Comments

I am getting this error : File "extractjson.py", line 6 if set['name'] == 'jim' ^ SyntaxError: invalid syntax
ah yes i forgot the colon at the end, that line should be if set['name'] == 'jim':

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.