Remember
JSON represents data as text. json.dumps() serializes supported Python values; json.loads() parses JSON back into Python values.
JSON represents data as text. json.dumps() serializes supported Python values; json.loads() parses JSON back into Python values.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
import json
data = {"score": 3, "ready": True}
text = json.dumps(data)
print(text)
restored = json.loads(text)
print(restored["score"])Top-level scope
{'score': 3, 'ready': True}Object 2 · str'{"score": 3, "ready": true}'Object 3 · dict{'score': 3, 'ready': True}JSON represents data as text. json.dumps() serializes supported Python values; json.loads() parses JSON back into Python values.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
import json
data = {"score": 3, "ready": True}
text = json.dumps(data)
print(text)
restored = json.loads(text)
print(restored["score"])
|
v
DISPLAYED RESULT
{"score": 3, "ready": true}
3
FINAL BINDINGS
data --> object 1 (dict)
text --> object 2 (str)
restored --> object 3 (dict)
object 1: {'score': 3, 'ready': True}
object 2: '{"score": 3, "ready": true}'
object 3: {'score': 3, 'ready': True}Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
import json
data = {"score": 3, "ready": True}
text = json.dumps(data)
print(text)
restored = json.loads(text)
print(restored["score"])Top-level scope
{'score': 3, 'ready': True}Object 2 · str'{"score": 3, "ready": true}'Object 3 · dict{'score': 3, 'ready': True}The example has finished. Compare the final output with the values and references above.
{"score": 3, "ready": true}
3
What do you expect this program to print?
import json
data = {"score": 3, "ready": True}
text = json.dumps(data)
print(text)
restored = json.loads(text)
print(restored["score"])JSON, short for JavaScript Object Notation, is a lightweight format for storing and transporting data. In Python, it plays a pivotal role when working with APIs, configuration files, or structured data exchange. The good news? Python makes JSON handling intuitive through its built-in json module.
JSON is a string-based format that represents data as key-value pairs. It's similar to Python dictionaries, which makes it easier for developers to interact with.
Start by importing Python's built-in module:
import json
Serialization means converting a Python object (like a dict) into a JSON string using json.dumps().
import json
data = {"name": "Alice", "age": 30, "is_admin": False}
json_string = json.dumps(data)
print(json_string)
{"name": "Alice", "age": 30, "is_admin": false}
json.dumps() converts Python data into a JSON-formatted string. Note how Python False becomes false in JSON, matching JSON syntax rules.
To parse a JSON string into Python data types, use json.loads():
json_data = '{"name": "Bob", "age": 25, "is_admin": true}'
parsed_data = json.loads(json_data)
print(parsed_data)
print(type(parsed_data))
{'name': 'Bob', 'age': 25, 'is_admin': True}
<class 'dict'>
The JSON string is turned into a Python dictionary. JSON's true becomes Python's True, and strings are decoded as Python strings.
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
data = {"language": "Python", "version": 3.10}
with open('data.json', 'w') as file:
json.dump(data, file)
Always use a context manager (with statement) to ensure the file is properly closed after reading/writing.
To make your JSON output more readable (e.g., for logging or debugging), use indent and sort_keys parameters:
data = {"name": "Zara", "age": 22, "city": "Delhi"}
print(json.dumps(data, indent=4, sort_keys=True))
{
"age": 22,
"city": "Delhi",
"name": "Zara"
}
Incorrect JSON will throw an exception. Always wrap your parsing logic in a try-except block:
json_string = '{"name": "Alex", "age": 28' # Missing closing brace
try:
data = json.loads(json_string)
except json.JSONDecodeError as e:
print("JSON decoding failed:", e)
JSON decoding failed: Expecting ',' delimiter: line 1 column 29 (char 28)
try-except to handle malformed datajson.dump() and json.load() for file operationsSuppose we want to encode a custom object:
import json
from datetime import datetime
class User:
def __init__(self, name):
self.name = name
self.timestamp = datetime.now()
def custom_encoder(obj):
if isinstance(obj, User):
return {"name": obj.name, "timestamp": obj.timestamp.isoformat()}
raise TypeError("Object not serializable")
user = User("Sam")
print(json.dumps(user, default=custom_encoder))
Whether you're building APIs, consuming web services, or simply storing structured data, JSON is a must-know skill in Python. With just a few functions from the json module, you can serialize, deserialize, and safely manipulate structured data. Remember to handle exceptions gracefully, validate data, and use pretty-printing to inspect JSON when debugging.
Connect what you noticed in the example with the idea below.
JSON represents data as text. json.dumps() serializes supported Python values; json.loads() parses JSON back into Python values.
json.dumps() returns a Python dictionary.
This is the misconception to avoid.Reaching the recap and completing the quizzes are separate milestones.