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

Instruction

Great! We can now store and read different types of data in JSON files. But we don't need to have a separate file for every employee or customer; we can store this information in a single JSON file. How? By using an array.

We read data from a file as before:

with open('employees.json', 'r') as file:
  employees = json.load(file)
{
  "employees": [
    {
      "name": "John",
      "age": 32
    },
    {
      "name": "Ana",
      "age": 45
    }
  ]
}

When a JSON file contains an array, then json.load() will load it as a Python list. Naturally, we can use it like a Python list – if we wanted information about the first employee in the list, we'd simply write:

employee[0]

If we wanted to calculate the mean age of all employees, we'd write:

sum = 0
count = 0
for x in employees:
  sum += x["age"]
  count += 1 
print("Mean age of employees", sum/count)

Exercise

Read the file named customers.json as customers.

Calculate the number of VIP clients among our customers, and print the result as shown below:

VIP clients: 00

Stuck? Here's a hint!

Loop over the elements of customers and check the "is_VIP" field::

vip_count = 0
for x in customers:
  if x["is_VIP"]:
    vip_count += 1