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