Can we work with more complicated objects in a JSON file? We certainly can! As you may recall from the intro, JSON also supports nested objects. We could have a file like this:
{
"employees": [
{
"first_name": "Emma",
"last_name": "Jones",
"age": 43
},
...
],
"departments": [
{
"name": "sales",
"number_of_employees":142
},
...
],
...
}
When we use json.load()
on such a file, we will get a nested dictionary.
Let's say we have information for a company with multiple departments. To get information about the departments, we first need to choose them, like so:
print(company["departments"])
This will give us a list of different departments.
Now, suppose we want to get the names of all departments with more than 50 employees:
for shop in company["shops"]:
if shop["number_of_employees"] > 50:
print(shop["name"])