简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM