COMPUTER PROGRAMMING 1 (PYTHON) • FILES & DATA I/O

JSON I/O — I can read/write simple JSON using the json module in supported tasks and explain the structure.

Learn how Python programs store and exchange structured data using the universal JSON format.

Historical Context & Motivation

Whenever two programs need to share information—like a weather app pulling data from a server, or a video game saving your progress—they need an agreed-upon format for organizing that data. In the early days of the web, developers used a verbose format called XML (Extensible Markup Language), which worked but was bulky and hard to read. Developers wanted something lighter, easier for humans to scan, and simpler for machines to process.

That need led to JSON (JavaScript Object Notation), a lightweight text format originally derived from JavaScript syntax but now used across virtually every programming language. JSON struck the perfect balance: it is compact enough for network transmission and readable enough for a developer to debug at a glance.

1999
JSON Conceived
Douglas Crockford begins promoting a minimal data-interchange format derived from JavaScript object literal syntax.
2002
json.org Launched
The JSON specification is published at json.org, providing a language-independent grammar that any programming language can implement.
2006
Python Adds json Module
Python 2.6 includes the built-in json module, making JSON reading and writing a one-import operation for Python programmers.
2013
ECMA-404 Standard
JSON is formalized as an international standard (ECMA-404), solidifying its role as the dominant data-interchange format on the web.
2020s
Universal Adoption
JSON is used by REST APIs, configuration files, databases (like MongoDB), and nearly every modern web and mobile application.

The central question this lesson addresses is: how do you take a Python data structure—like a dictionary or a list—turn it into a JSON text file, and then read it back into Python later? Understanding this workflow is essential for building any program that saves settings, communicates with web services, or processes datasets.

Core Principles & Definitions

Before writing any code, you need to understand what JSON actually looks like and how its pieces map onto Python data types. JSON is built from just two container structures—objects and arrays—plus a handful of simple value types. Once you see the mapping, reading and writing JSON in Python feels natural.

1

JSON Object → Python dict

A JSON object is a collection of key-value pairs enclosed in curly braces { }. Keys must be strings. In Python, this becomes a dict.
2

JSON Array → Python list

A JSON array is an ordered sequence of values enclosed in square brackets [ ]. In Python, this maps to a list.
3

Primitive Values

JSON supports strings (in double quotes), numbers (int or float), booleans (true / false), and null. Python converts these to str, int/float, bool, and None.
4

Serialization & Deserialization

Serialization converts a Python object into a JSON string (writing). Deserialization converts a JSON string back into a Python object (reading).
5

The json Module

Python's built-in json module provides four key functions: json.dump(), json.dumps(), json.load(), and json.loads(). The "s" stands for "string."
✦ KEY TAKEAWAY
Think of JSON like a universal packing list for shipping data. Just as a moving company labels boxes with contents and counts, JSON labels every piece of data with a key name and a value. Python's json module is the translator that packs Python objects into labeled JSON boxes (serialization) and unpacks JSON boxes back into Python objects (deserialization).

Visual Explanation — JSON Structure Map

The diagram shows the one-to-one mapping between JSON data types (left) and Python data types (right). Arrows indicate the direction of conversion: json.load() reads JSON into Python, and json.dump() writes Python out as JSON.

Notice that JSON booleans use lowercase (true and false) while Python capitalizes them (True and False). Similarly, JSON uses null where Python uses None. The json module handles these translations automatically, so you don't have to worry about converting them yourself.

How the json Module Works

Python's json module gives you four main functions, and understanding when to use each one is the key to mastering JSON I/O. Two of them work with files and two work with strings. The naming convention makes this easy to remember: the functions ending in "s" (for "string") work with strings in memory, while the functions without "s" work directly with file objects.

Writing JSON

WRITE TO FILE
json.dump(data, file_object, indent=4)
data — the Python dict or list to serialize. file_object — an open file in write mode. indent — optional parameter that pretty-prints the JSON with the given number of spaces.
WRITE TO STRING
json_string = json.dumps(data, indent=4)
Returns a str containing the JSON text. Useful when you want to inspect the JSON before saving, or send it over a network.

Reading JSON

READ FROM FILE
data = json.load(file_object)
Reads the entire file, parses the JSON text, and returns the corresponding Python object (usually a dict or list).
READ FROM STRING
data = json.loads(json_string)
Parses a JSON-formatted str and returns the corresponding Python object. Commonly used when receiving JSON from a web API.
💡 Memory Trick
The "s" at the end of dumps and loads stands for string. No "s" = works with a file. Has an "s" = works with a string.

Anatomy of a JSON File

Let's look at a realistic JSON file and break down every element. Imagine you are building a simple contact book application. Each contact has a name, age, email, a list of hobbies, and an indicator of whether they are active. Below is a JSON file that stores one such contact along with the application's metadata.

This annotated JSON file shows how keys (cyan), string values (green), numbers (amber), and booleans (red) are color-coded. Notice how the outer object contains a nested array of contact objects, demonstrating JSON's ability to represent complex, hierarchical data.

There are a few rules to remember about JSON syntax. First, all keys and string values must be enclosed in double quotes—single quotes are not valid in JSON (even though Python allows them). Second, trailing commas after the last item in an object or array are not allowed, which is a common source of errors when hand-editing JSON files. Third, JSON does not support comments, so you cannot add # or // annotations inside a JSON file.

Worked Example — Save and Load a Student Record

Let's walk through a complete example where we create a Python dictionary representing a student, write it to a JSON file, and then read it back into Python.

Writing and Reading a Student Record with JSON
1
Step 1 — Import the json moduleAt the top of your Python script, import the built-in json module. No installation is needed—it comes with every Python distribution. import json
The json module is now available for use.
2
Step 2 — Create the Python data structureBuild a dictionary with the student's information. This dict can contain nested lists and other data types. student = {"name": "Jordan", "grade": 11, "gpa": 3.85, "courses": ["Python", "Algebra 2", "English"], "honor_roll": True}
A dict with strings, an int, a float, a list, and a bool.
3
Step 3 — Write the dict to a JSON fileOpen a file in write mode ("w") and use json.dump() to serialize the dict into that file. The indent=4 parameter makes the output human-readable. with open("student.json", "w") as f: json.dump(student, f, indent=4)
A file named student.json is created with pretty-printed JSON content.
4
Step 4 — Read the JSON file back into PythonOpen the same file in read mode ("r") and use json.load() to deserialize the JSON text back into a Python dictionary. with open("student.json", "r") as f: loaded = json.load(f)
The variable loaded is now a Python dict identical to the original student dict.
5
Step 5 — Access data from the loaded dictYou can now use the loaded data just like any Python dictionary. Access individual values by key, iterate over lists, or check boolean flags. print(loaded["name"]) # Jordan print(loaded["courses"][0]) # Python print(loaded["honor_roll"]) # True
The program prints: Jordan, Python, True — confirming the data round-tripped successfully.

Strengths, Limitations & Common Pitfalls

JSON is incredibly popular, but it is not perfect for every situation. Knowing its strengths and limitations will help you choose the right tool for each project and avoid frustrating bugs.

JSON strengths vs. limitations for typical programming tasks
AspectStrengths ✅Limitations ⚠️
ReadabilityHuman-readable text format; easy to inspect and debug in any text editor.Large files can become hard to navigate without specialized tools.
Data TypesCovers the most common types: strings, numbers, booleans, null, arrays, and objects.Cannot store Python-specific types like tuples, sets, datetime objects, or custom classes without extra conversion.
Cross-LanguageNearly every programming language has a JSON library, making it ideal for data exchange.Slight differences in number precision between languages can cause rare edge-case bugs.
File SizeMuch more compact than XML for the same data.Binary formats like Protocol Buffers or MessagePack are smaller and faster for huge datasets.
CommentsThe strict format avoids ambiguity; parsers are fast and simple.No support for comments — you cannot annotate a JSON file with explanations.
✦ WHEN TO USE JSON
Use JSON when you need to save or transmit simple, structured data—like user settings, quiz scores, or API responses. If you need to store images, complex scientific data, or millions of rows, look into specialized formats like CSV, SQLite, or binary serialization instead.

Connection to Advanced Topics

The JSON skills you are building now form the foundation for many advanced topics in software development. As you progress, you will encounter more complex scenarios that build directly on json.load() and json.dump().

How basic JSON I/O skills connect to advanced programming topics
What You Learn NowWhere It Leads
Reading/writing JSON files locallyConsuming REST APIs over the internet (e.g., weather data, social media APIs) using the requests library
Simple dicts and lists in JSONWorking with deeply nested JSON from real-world APIs and databases like MongoDB
Using indent for pretty-printingCustom serializers using json.JSONEncoder to handle datetime objects, sets, and custom classes
Basic type mapping (dict, list, str, int)Schema validation with libraries like jsonschema to ensure data conforms to an expected structure

One especially exciting next step is learning to interact with web APIs. When you send a request to a server—say, asking for today's weather in your city—the server typically responds with a JSON string. You already know how to parse that string with json.loads() and extract the data you need. The skills from this lesson transfer directly.

Practice Problems

PROBLEM 1 — CONCEPTUAL
What is the difference between json.dump() and json.dumps()? When would you use each one?
PROBLEM 2 — BASIC CALCULATION
Given the Python dictionary pet = {"name": "Luna", "species": "cat", "age": 3, "vaccinated": True}, write the Python code to save this dictionary to a file called pet.json with an indentation of 2 spaces.
PROBLEM 3 — INTERMEDIATE
You have a JSON file called scores.json that contains: {"math": 92, "science": 88, "english": 95}. Write a Python program that reads this file, adds a new key "history": 90, and then writes the updated dictionary back to the same file.
PROBLEM 4 — APPLIED
You are building a simple to-do list app. Write a program that creates a list of three to-do items (each item is a dictionary with keys "task", "done", and "priority"), saves the list to todos.json, loads it back, and prints only the tasks that are not yet done.
PROBLEM 5 — CRITICAL THINKING
A student writes the following code and gets an error. Identify at least two problems and explain how to fix them: import json data = {"name": "Sam", "scores": (95, 88, 72), "joined": None} with open('output.json', 'w') as f: json.dump(data, f) with open('output.json') as f: result = json.load(f) print(type(result['scores'])) # What type is this now?

Lesson Summary

JSON (JavaScript Object Notation) is a lightweight, text-based format for storing and exchanging structured data. A JSON file is built from two container types—objects (curly braces) and arrays (square brackets)—plus primitive values: strings, numbers, booleans, and null. In Python, objects map to dicts, arrays map to lists, and the remaining types map naturally to str, int/float, bool, and None.

Python's built-in json module provides four essential functions: json.dump() writes to a file, json.dumps() returns a string, json.load() reads from a file, and json.loads() parses a string. The process of converting Python objects to JSON is called serialization, and the reverse is deserialization. Remember that JSON requires double quotes, forbids trailing commas and comments, and does not support Python-specific types like tuples or sets. Mastering JSON I/O prepares you for working with web APIs, configuration files, and data-driven applications.

Varsity Tutors • Computer Programming 1 (Python) • JSON I/O — I can read/write simple JSON using the json module in supported tasks and explain the structure.