Python JSON Tutorial

Let’s look at json tutorial

  1. Notice

    JSON represents data as text. json.dumps() serializes supported Python values; json.loads() parses JSON back into Python values.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
import json
data = {"score": 3, "ready": True}
text = json.dumps(data)
print(text)
restored = json.loads(text)
print(restored["score"])
Live state

Top-level scope

data→Object 1
text→Object 2
restored→Object 3
Object 1 · dict{'score': 3, 'ready': True}Object 2 · str'{"score": 3, "ready": true}'Object 3 · dict{'score': 3, 'ready': True}
This step

JSON represents data as text. json.dumps() serializes supported Python values; json.loads() parses JSON back into Python values.

Picture json tutorial

JSON represents data as text. json.dumps() serializes supported Python values; json.loads() parses JSON back into Python values.

Image brief

Alt text
A diagram for Python JSON Tutorial. Instructions: import json data = {"score": 3, "ready": True} text = json.dumps(data) print(text) restored = json.loads(text) print(restored["score"]). Displayed result: {"score": 3, "ready": true} 3. The final example bindings are 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}
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python JSON Tutorial". Teaching focus: JSON represents data as text. json.dumps() serializes supported Python values; json.loads() parses JSON back into Python values. Depict exactly the relationships and labels in this reference diagram: 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} Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: A diagram for Python JSON Tutorial. Instructions: import json data = {"score": 3, "ready": True} text = json.dumps(data) print(text) restored = json.loads(text) print(restored["score"]). Displayed result: {"score": 3, "ready": true} 3. The final example bindings are 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}

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
import json
data = {"score": 3, "ready": True}
text = json.dumps(data)
print(text)
restored = json.loads(text)
print(restored["score"])
Live state

Top-level scope

data→Object 1
text→Object 2
restored→Object 3
Object 1 · dict{'score': 3, 'ready': True}Object 2 · str'{"score": 3, "ready": true}'Object 3 · dict{'score': 3, 'ready': True}
This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
{"score": 3, "ready": true}
3

What do you expect this program to print?

What does this example display?

import json
data = {"score": 3, "ready": True}
text = json.dumps(data)
print(text)
restored = json.loads(text)
print(restored["score"])
What does this example display?
Choose one answer. You can try again.

Answer and explanation

{"score": 3, "ready": true} 3

Follow the printed values in order. The output is: {"score": 3, "ready": true} 3

Which explanation matches what you learned?

Which explanation matches what you learned?
Choose one answer. You can try again.

Answer and explanation

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.

Introduction to JSON in Python

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.

What Is JSON?

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.

Why Use JSON in Python?

  • Interchange data between frontend and backend (especially via APIs)
  • Save application settings or configurations
  • Serialize Python objects for storage or transmission

Importing the JSON Module

Start by importing Python's built-in module:

import json

Converting Python Objects to JSON (Serialization)

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}

Explanation

json.dumps() converts Python data into a JSON-formatted string. Note how Python False becomes false in JSON, matching JSON syntax rules.

Converting JSON to Python Objects (Deserialization)

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'>

Explanation

The JSON string is turned into a Python dictionary. JSON's true becomes Python's True, and strings are decoded as Python strings.

Reading JSON from a File

with open('data.json', 'r') as file:
    data = json.load(file)
    print(data)

Writing JSON to a File

data = {"language": "Python", "version": 3.10}
with open('data.json', 'w') as file:
    json.dump(data, file)

Tip

Always use a context manager (with statement) to ensure the file is properly closed after reading/writing.

Pretty-Printing JSON

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"
}

Handling Errors While Parsing JSON

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)

Common Checks and Best Practices

  • Ensure the JSON string is valid before parsing
  • Use try-except to handle malformed data
  • Use json.dump() and json.load() for file operations
  • Validate encoding types when reading non-UTF-8 files

Advanced: Custom Encoding with json.JSONEncoder

Suppose 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))

Summary

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.

What to remember

Connect what you noticed in the example with the idea below.

Remember

JSON represents data as text. json.dumps() serializes supported Python values; json.loads() parses JSON back into Python values.

Watch out for this idea

json.dumps() returns a Python dictionary.

This is the misconception to avoid.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Python datetime Tutorial →