We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Parsing JSON

Almost every modern API gives you JSON. Luckily, JSON maps nicely onto normal Python data structures:

  • JSON objects become dicts
  • JSON arrays become lists

Python's built-in json.loads() can convert a JSON string:

json_string = '{"title": "The Matrix", "year": 1999}'
data = json.loads(json_string)

print(data["title"])
# The Matrix
print(data["year"])
# 1999

After that call, data is a normal Python dictionary that you can work with like any other.

Nested Data

Real JSON is usually nested. You can drill down one level at a time with bracket notation:

data = json.loads(
    '{"show": {"title": "Breaking Bad", "network": "AMC"}, "rating": {"score": 9.5}}'
)

print(data["show"]["title"])
# Breaking Bad
print(data["rating"]["score"])
# 9.5

Each pair of brackets goes one level deeper.

Missing Keys

Real API data is messy, and sometimes you try to grab a value from a key that doesn't exist:

data = {"title": "Breaking Bad"}

seasons = data["seasons"]
# raises KeyError: 'seasons'

Fortunately, the .get() let's you handle that case gracefully, it simply returns None if the key doesn't exist:

seasons = data.get("seasons")
# seasons = None

Alternatively, you can provide a default value to return instead of None:

seasons = data.get("seasons", 5)
# seasons = 5

Use bracket notation when a field must exist. Use .get() when you're not sure and a default value is acceptable.

Assignment

SnackStack's API returns device readings as JSON strings. Before the analytics team can use them, we need to parse the JSON and pull out only the fields we care about.

Complete the parse_device_reading function. It accepts a JSON string and returns a dictionary with the reading details.

You should print() the json_string manually to see what you're working with.