Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reading a JSON in one function to use values in other functions

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading