

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Data Formats
incomplete
2: Parsing JSON
incomplete
3: Variable-Depth JSON
incomplete
4: Fetching JSON
incomplete
5: CSV Files
incomplete
6: CSV Type Conversion
incomplete
7: Filtering CSV Rows
incomplete
8: Writing CSV Files
incomplete
9: Appending to CSV Files
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Almost every modern API gives you JSON. Luckily, JSON maps nicely onto normal Python data structures:
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.
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.
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.
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.