Legends ofPythos
Claim your name
Working with Data

Reading and writing JSON

Lesson 12 of 14

Watch the lesson1:11 ยท with Torsten
JSON (JavaScript Object Notation) is a lightweight text format designed specifically to move data between different systems.

Think of it like universal packaging: you can put your Python dictionary inside, ship it across the internet in plain text, and unpack it on another machine. It looks almost exactly like how we write dictionaries and lists here.

Why use JSON?

You will see this everywhere: when a web app talks to its server, or when you save your high scores in a game. It is easy for humans to read and write.

Here is the same data as both JSON text and a Python dictionary:
{"name": "Alice", "age": 30}
{'name': 'Alice', 'age': 30}

Turning data into text: dumps()

import json

data = {'name': 'Alice', 'age': 30}
json_text = json.dumps(data)
print(json_text)
Converting a Python dictionary to JSON text
dumps is short for dump string. It takes your live data and returns it as a string you can save or send.

Turning text back into data: loads()

import json

json_text = '{"name": "Alice", "age": 30}'
data = json.loads(json_text)
print(data['name'])
Parsing JSON text back into a dictionary
loads is short for load string. It takes the string and gives you back an object with keys, values, and types.

Your turn

0 of 2 solved

Exercise 1

+35 XP
Convert this Python dictionary into a JSON string using json.dumps(). Print the result.
data = {'city': 'Paris', 'visits': 3}
The output should be: {"city": "Paris", "visits": 3}
data = {'city': 'Paris', 'visits': 3}

Run your code to check it against the tests.

Exercise 2

+35 XP
Parse this JSON string into a Python dictionary called data using json.loads(), then print the value of its 'language' key.
json_str = '{"name": "Pythos", "language": "Python", "version": 3}'
The output should be: Python
json_str = '{"name": "Pythos", "language": "Python", "version": 3}'

Run your code to check it against the tests.