MSIT

Read JSON

JSON is text that stores a dictionary. The json module is part of the standard library.

json.loads(text) turns that text into a dictionary. data["score"] reads one field.

Why the json module exists

Programs trade records as text: a score, a name, a list of ids. JSON is a common shape for that text. It uses braces, quotes, and colons. You could scan those characters yourself. You would then have to handle spaces, nested braces, and numbers that should stay numbers. The json module already does that work. json.loads means "load from a string."

The module exists so your function can ask for a field by key instead of hunting through punctuation.

The JSON logo
JSON is a text format. The json module turns that text into Python values.

JSON is text. A dictionary is a Python value. The json module is the bridge between them.

Text is not yet a dictionary

A JSON object looks like a dictionary, but until you parse it, it is a string. Quotes, braces, and colons are characters. text["score"] would fail, because a string's keys are not field names.

  • json.loads reads the text and builds a dictionary.
  • json.dumps does the reverse: it turns a dictionary into text. This page only needs loads.

A JSON number becomes an int or a float. A JSON string stays text. The key you want here is score, and the value under that key is a number.

That prints 12. data is {"player": "Kai", "score": 12} as a dictionary, not as text. The outer Python quotes are single quotes so the JSON double quotes can sit inside the string unchanged.

Match the call with what it returns.

  • math.sqrt
  • json.loads

Why call json.loads before reading score?

A worked example

score takes JSON text and returns the number stored under score. The function must work for any text that has that key, not for one fixed string.

  1. Import json.
  2. Parse the parameter with json.loads(text).
  3. Return data["score"].

Trace a call with '{"player": "Kai", "score": 12}'. loads builds a dictionary with two keys. data["score"] is the integer 12. That integer is the return value. A different string, with a different number under the same key, follows the same three steps. If the key is missing, data["score"] raises KeyError. The texts in this lesson include score.

This program cannot be stepped through.

Click the line that turns JSON text into a dictionary.



Put the lines in an order that defines score and returns the number under that key.

    return text
    return data["score"]
def score(text):
    data = json.loads(text)
import json

Import json in the editor. The starter does not import it for you.

Exercise

Write a function named score that takes JSON text and returns the number stored under the key score.

Write a function named score that takes JSON text and returns the number stored under the key score.

Output