Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Reading JSON files
9. JSON with nested objects
Summary and Review

Instruction

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"])

Exercise

Read the file named morgana_inc.json into memory as morgana. Find the street address of the shop in the city of Santa Cruz de El Seibo (print the street).