Python for data

Lesson 11 of 15

Lesson ยท 16 min

JSON data

Data with a shape

A CSV file is a flat table of rows and columns. Some data does not fit a table. A station has opening hours, and the hours have a start and an end. JSON is a text format for data with such a shape. Web services send JSON, programs keep their settings in JSON, and language models read and write JSON.

{
  "name": "Harbor Gate",
  "docks": 16,
  "active": true,
  "hours": {"from": "05:00", "to": "23:00"},
  "tags": ["harbor", "ferry"],
  "closed_since": null
}

JSON looks like Python. The table shows what each part becomes when Python reads it.

JSON Python
an object in braces { } a dictionary
a list in brackets [ ] a list
text in double quotation marks a string
a number an int or a float
true and false True and False
null None

Numbers stay numbers. You do not convert them. This is an important difference from CSV.

Read JSON

The function json.load reads a file.

import json

with open("station.json", encoding="utf-8") as file:
    station = json.load(file)

print(station["docks"] + 1)       # 17
print(station["hours"]["from"])   # 05:00
print(station["tags"][0])         # harbor

You get a value inside a value step by step: first the key hours, and then the key from.

json.loads does the same for a text that you already have. The s at the end means "string".

point = json.loads('{"x": 2, "y": 5}')
print(point["y"])   # 5

Write JSON

json.dumps makes JSON text from a Python value. indent=2 puts each value on its own line.

text = json.dumps({"name": "Old Mill", "active": True}, indent=2)
print(text)
{
  "name": "Old Mill",
  "active": true
}

One value on each line

Logs and large sets of data often use a simpler form. Each line of the file is one complete JSON value. The name of this form is JSON Lines, and the file name often ends in .jsonl. json.load cannot read such a file, because the whole file is not one JSON value. Read it line by line.

events = []
with open("events.jsonl", encoding="utf-8") as file:
    for line in file:
        if line.strip() != "":
            events.append(json.loads(line))

The test sets of AI apps often use this form.

Your turn

This lesson has two data files. stations.json is one JSON object. repairs.jsonl has one repair on each line, and one line is empty. Do the tasks in order.

Tasks

5 to do

  1. Task 1, not checked yet. Import the json module. Read stations.json into a variable named data.

  2. Task 2, not checked yet. Make a list names with the name of each station in data.

  3. Task 3, not checked yet. Make a variable active_docks with the total number of docks of the stations where active is true.

  4. Task 4, not checked yet. Write a function read_json_lines(file_name). It reads a file that has one JSON value on each line, and it returns the list of the values. It skips empty lines.

  5. Task 5, not checked yet. Make a dictionary summary with four keys: stations (the number of stations), active_docks, repairs (the number of repairs in repairs.jsonl) and repair_cost (the total cost of the repairs). Make a variable summary_text with the JSON text of summary, with an indent of 2 spaces.

Task 1 of 5

Import the json module. Read stations.json into a variable named data.

All tasks

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.