[SOLVED] Reading a JSON in one function to use values in other functions

Issue

In python, how do I read a json in one function, to access its values for another function? I only want to access a single value (‘Scenario’) at a time.

Example json –

{
    "scenario_A": {
        "type": "animal",
        "name": "alligator",
        "ext":  ".jpg",
    },

    "scenario_B": {
        "type": "fruit",
        "name": "banana",
        "ext":  ".png",
    }
}

Example Script – result should be a print statement of number of .jpgs in the ‘alligator’ folder

import json

json_path = "C:\config.json"
image_dir = "C:\images"
scenario_type = "scenario_A"

def process(load_json, find_images)
    load_json(json_path, scenario_type)
    find_images(image_dir, load_json)

def load_json(json_path, scenario_type):
    json_read = json.load(open(json_path))
    return json_read[scenario_type]
  
def find_images(image_dir,load_json):
    images = [f for f in os.listdir(os.path.join(image_dir, load_json["name"]))
                      if f.endswith(load_json["ext"])]
    print(f"\n{len(images)} total")

if __name__ == "__main__":
    process()

But instead I get –

TypeError: ‘function’ object is not subscriptable.

Solution

There are a few issues with your code. You need to assign a variable as the output of your load_json function and then use that instead of the function.

You also should explicitly pass all variables to a function to ensure the code executes repeatably.

See below for edited code.

import json

json_path = "C:\config.json"
image_dir = "C:\images"
scenario_type = "scenario_A"

def process(json_path, image_dir, scenario_type):
    current_json = load_json(json_path, scenario_type)
    find_images(image_dir, current_json)

def load_json(json_path, scenario_type):
    json_read = json.load(open(json_path))
    return json_read[scenario_type]
  
def find_images(image_dir, json):
    images = [f for f in os.listdir(os.path.join(image_dir, json["name"]))
                      if f.endswith(json["ext"])]
    print(f"\n{len(images)} total")

if __name__ == "__main__":
    process(json_path, image_dir, scenario_type)

Answered By – Pepsi-Joe

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.