LearnContact
Lesson 5222 min read

JSON Handling

Learn how to convert Python objects to and from JSON using the json module, including reading and writing JSON files.

Introduction

JSON (JavaScript Object Notation) is the most common format used to exchange data between programs, APIs, and files. Whenever you call a web API, save application settings, or send data between a Python backend and a JavaScript frontend, JSON is almost always involved.

Python's built-in json module makes it simple to convert between Python objects like dictionaries and lists and their JSON text representation, in either direction.

What You Will Learn
  • What JSON is and why it is used everywhere.
  • How to convert Python data to a JSON string with json.dumps().
  • How to convert a JSON string back to Python with json.loads().
  • How to read and write JSON files directly with json.load() and json.dump().
  • Common pitfalls, like string-only keys and None becoming null.

What is JSON?

JSON is a lightweight, text-based data format that looks a lot like a Python dictionary. It is language-independent, which means a JSON file created by a Python program can be read by JavaScript, Java, or almost any other language.

Text-Based

JSON is plain text, so it can be stored in files, sent over networks, and read by humans.

Key-Value Pairs

JSON objects look like Python dictionaries, using keys and values.

Language-Independent

Almost every programming language has a library for reading and writing JSON.

Used by APIs

Most web APIs send and receive data in JSON format.

Example JSON
{
  "name": "Alex",
  "age": 16,
  "is_student": true,
  "courses": ["Python", "JavaScript"]
}

The json Module

Python includes a built-in json module, so there is nothing to install. Import it and you get four main functions to remember.

json.dumps()

Convert a Python object into a JSON string.

json.loads()

Convert a JSON string into a Python object.

json.dump()

Write a Python object directly to a JSON file.

json.load()

Read a JSON file directly into a Python object.

Remembering the Names
  • Names ending in "s" (dumps, loads) work with strings.
  • Names without "s" (dump, load) work with files.

Converting Python to JSON

json.dumps() ("dump string") takes a Python object — usually a dictionary or list — and returns a JSON-formatted string.

dumps_example.py
import json

data = {
    "name": "Alex",
    "age": 16,
    "is_student": True,
    "grades": [88, 92, 79]
}

json_string = json.dumps(data)
print(json_string)
print(type(json_string))
Output
{"name": "Alex", "age": 16, "is_student": true, "grades": [88, 92, 79]}
<class 'str'>

Notice that Python's True became JSON's lowercase true. The json module automatically translates Python-specific values into their JSON equivalents.

Converting JSON to Python

json.loads() ("load string") does the opposite — it takes a JSON string and parses it back into native Python objects like dictionaries and lists.

loads_example.py
import json

json_string = '{"name": "Maya", "age": 15, "active": true}'

data = json.loads(json_string)
print(data)
print(type(data))
print(data["name"])
Output
{'name': 'Maya', 'age': 15, 'active': True}
<class 'dict'>
Maya

Once parsed, the result behaves exactly like any normal Python dictionary — you can index it, loop over it, or modify it.

Pretty-Printing with indent

By default, json.dumps() produces compact, single-line output. Passing the indent parameter makes the output far easier to read, which is especially useful when saving configuration files or debugging.

pretty_print.py
import json

data = {"name": "Alex", "hobbies": ["chess", "coding"], "age": 16}

pretty = json.dumps(data, indent=4)
print(pretty)
Output
{
    "name": "Alex",
    "hobbies": [
        "chess",
        "coding"
    ],
    "age": 16
}
Sorting Keys

Add sort_keys=True alongside indent to always output dictionary keys in alphabetical order — handy for consistent diffs when JSON files are stored in version control.

Reading & Writing JSON Files

Most real programs do not just convert JSON to strings in memory — they save it to a file so the data persists between runs. json.dump() and json.load() work directly with an open file object.

write_json.py
import json

data = {"username": "coder123", "score": 950, "level": 7}

with open("profile.json", "w") as file:
    json.dump(data, file, indent=4)

print("Saved profile.json")
Output
Saved profile.json
read_json.py
import json

with open("profile.json", "r") as file:
    data = json.load(file)

print(data)
print("Score:", data["score"])
Output
{'username': 'coder123', 'score': 950, 'level': 7}
Score: 950
dump vs dumps
  • json.dump(data, file) writes directly to an open file — no string is created.
  • json.dumps(data) returns a string you would still need to write yourself.
  • Always prefer json.dump()/json.load() when working with files.

Nested JSON Structures

JSON objects frequently contain other objects and lists nested inside them. Python's json module handles this automatically — nested JSON objects simply become nested dictionaries and lists.

nested_json.py
import json

data = {
    "student": "Riya",
    "address": {
        "city": "Pune",
        "zip": "411001"
    },
    "subjects": [
        {"name": "Math", "score": 91},
        {"name": "Science", "score": 87}
    ]
}

json_string = json.dumps(data, indent=2)
print(json_string)

parsed = json.loads(json_string)
print(parsed["address"]["city"])
print(parsed["subjects"][0]["name"])
Output
{
  "student": "Riya",
  "address": {
    "city": "Pune",
    "zip": "411001"
  },
  "subjects": [
    {
      "name": "Math",
      "score": 91
    },
    {
      "name": "Science",
      "score": 87
    }
  ]
}
Pune
Math

You can drill down into nested data using regular dictionary and list indexing, chained together one level at a time.

Python-to-JSON Type Conversion

The json module maps Python types to JSON types (and back) using a fixed set of rules. Knowing this table helps you predict exactly what your output will look like.

Python TypeJSON TypeExample
dictobject{"a": 1}
list, tuplearray[1, 2, 3]
strstring"hello"
int, floatnumber42, 3.14
True / Falsetrue / falsetrue
Nonenullnull

Common Pitfalls

A few behaviors trip up almost every beginner working with JSON for the first time.

Assuming JSON keys can be any type
data = {1: "one", 2: "two"}
print(json.dumps(data))
# {"1": "one", "2": "two"}  <- keys became strings!
Forgetting None becomes null (and back)
data = {"middle_name": None}
print(json.dumps(data))
# {"middle_name": null}
Using single quotes in a JSON string
bad = "{'name': 'Alex'}"
json.loads(bad)  # raises json.JSONDecodeError
Not handling missing/corrupt files
try:
    with open("data.json") as f:
        data = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
    data = {}

Best Practices

  • Use json.dump()/json.load() for files instead of manually building strings.
  • Use indent=4 whenever a human might read the JSON output.
  • Wrap file and parsing operations in try/except to handle missing or malformed files.
  • Remember that dictionary keys always become strings in JSON.
  • Validate data types after loading if the JSON comes from an untrusted source.

Frequently Asked Questions

Is JSON the same as a Python dictionary?

They look similar, but JSON is a text format, while a Python dictionary is an in-memory object. json.loads() and json.dumps() convert between the two.

Can I convert a custom Python class to JSON?

Not directly — json.dumps() only understands basic types like dict, list, str, int, float, bool, and None. For custom objects, you typically convert them to a dictionary first, or supply a custom "default" function.

What happens if my JSON string has a syntax error?

json.loads() or json.load() will raise a json.JSONDecodeError, which tells you the exact line and column where parsing failed.

Do I need to close the file after json.dump()?

Not manually — using a "with open(...) as file:" block automatically closes the file for you when the block ends.

Can JSON store tuples?

No. JSON has no tuple type, so Python tuples are converted to JSON arrays (lists) and come back as lists, not tuples, when loaded.

Key Takeaways

  • JSON is a text-based, language-independent format for exchanging data.
  • json.dumps()/json.loads() convert between Python objects and JSON strings.
  • json.dump()/json.load() read and write JSON directly to and from files.
  • The indent parameter makes JSON output human-readable.
  • JSON keys are always strings, and Python's None always becomes JSON's null.

Summary

The json module is one of the most practical tools in Python's standard library, letting you move data between Python programs, files, and web APIs with just a few function calls.

In this lesson, you learned how to serialize and deserialize JSON with dumps()/loads(), work with JSON files using dump()/load(), pretty-print with indent, and avoid the most common pitfalls involving keys and None.

Lesson 52 Completed
  • You can convert Python objects to and from JSON strings.
  • You can read and write JSON files directly.
  • You understand how Python types map to JSON types.
  • You are ready to learn about handling CSV files.
Next Lesson →

CSV Handling