0

I have a JSON file like this; { "name" : "maria", "age" : "40", "adress" : "usa" }

and I want to apply a function which takes as arguments the name, age, address

my basic function is like this:

def get(name, age, address):
    print(name has (age) years old and a house in (address)

the question is how to feed the function from the JSON file

RoadRunner
  • 25,803
  • 6
  • 42
  • 75
daniel
  • 11
  • 1

1 Answers1

0

For this simple test.json JSON file:

{ "name" : "maria", "age" : "40", "address" : "usa" }

We can deserialize the JSON into a dictionary with json.load, then pass the name, age and address values to the get() function:

from json import load

def get(name, age, address):
    print(f"{name} has {age} years old and a house in {address}")

with open("test.json") as f:
    data = load(f)
    get(data["name"], data["age"], data["address"])

I used Formatted string literals to insert the name, age and address into a formatted string. These are also known as f-strings.

It might also be safer to use dict.get() to fetch the values and give a default value of None, since you could get a KeyError if the key doesn't exist. You can also specify any other default value.

get(data.get("name"), data.get("age"), data.get("address"))

Output:

maria has 40 years old and a house in usa
RoadRunner
  • 25,803
  • 6
  • 42
  • 75