Files & DataIntermediate8 min52 / 63

Working with JSON

Learn how to read, write, and work with JSON — the universal data format powering APIs and config files everywhere.

Imagine you want to send a Python dictionary to a friend over the internet, or save your app's settings to a file so they survive a restart. You can't just send a Python object — the other side might be running JavaScript, Go, or something else entirely. JSON (pronounced "JAY-sun") solves this. It's a simple text format that almost every programming language on the planet can read and write. Once you understand JSON, you can talk to web APIs, read config files, and share data with ease.

See it in action

Visual walkthrough1 / 5
1

JSON: The Web's Common Language

JSON is a simple text format that every programming language understands. It's how Python talks to APIs, saves config files, and shares data with the world.

JSON looks almost identical to Python dicts — that's intentional!

#What Does JSON Look Like?

JSON looks a lot like Python dictionaries and lists — because Python's dict syntax was actually inspired by similar ideas. Here is a small JSON snippet:

`` { "name": "Alice", "age": 30, "hobbies": ["reading", "cycling"], "active": true } ``

Notice a few things: - Keys are always double-quoted strings (not single quotes) - true/false are lowercase (not Python's True/False) - null means nothing (Python's None) - Numbers, strings, lists, and nested objects are all supported

Think of it like

JSON is like a universal shipping box

Think of JSON as a standard cardboard box that every courier in the world knows how to handle. You pack your Python data into the box (encoding), ship it, and the recipient unpacks it into their language's own format (decoding). The box itself is just text.

#The JSON Type Map

Python and JSON types correspond to each other almost perfectly:

| JSON | Python | |---|---| | object {} | dict | | array [] | list | | string "hi" | str | | number 42 / 3.14 | int / float | | true / false | True / False | | null | None |

When you convert Python to JSON, Python automatically uses these mappings — and back again when you load JSON into Python.

#Importing the json Module

Python ships with a built-in json module — no installation needed. Just import it at the top of your file.

The json module is part of Python's standard library
import json

print("json module ready!")

#From String to Python: json.loads

When you receive JSON data — say, from a web API — it arrives as a plain string. json.loads() ("load string") converts that string into a real Python object you can work with.

json.loads turns a JSON string into a Python dict
import json

json_string = '{"name": "Alice", "age": 30, "active": true}'

data = json.loads(json_string)

print(type(data))       # it's a dict now!
print(data["name"])     # access like any dict
print(data["active"])   # true became True

#From Python to String: json.dumps

json.dumps() ("dump string") does the opposite — it takes a Python object and returns a JSON-formatted string. This is what you use when you want to send data to an API or write it to a file as text.

json.dumps converts a Python dict to a JSON string
import json

user = {
    "name": "Bob",
    "score": 42,
    "verified": False,
    "tags": ["python", "beginner"]
}

json_string = json.dumps(user)
print(json_string)
print(type(json_string))

#Pretty-Printing with indent

By default, json.dumps() squashes everything onto one line — hard to read! Pass indent=2 (or any number) to get nicely formatted output. You can also use sort_keys=True to alphabetize the keys, which makes output consistent and easy to compare.

indent=2 and sort_keys=True make JSON human-friendly
import json

config = {
    "theme": "dark",
    "fontSize": 14,
    "plugins": ["linter", "formatter"]
}

pretty = json.dumps(config, indent=2, sort_keys=True)
print(pretty)
Tip

Use indent=2 when saving files humans will read

Compact JSON saves a tiny bit of space, but pretty-printed JSON is much easier to review, debug, and edit. Use indent=2 for config files and logs. Skip it for data you're sending over a network where size matters.

#Reading JSON from a File: json.load

json.load() (no "s") reads directly from a file object. You don't have to read the file into a string first — just open the file and hand it to json.load().

json.load reads JSON directly from an open file
import json

# Imagine config.json contains:
# {"host": "localhost", "port": 8080, "debug": true}

with open("config.json", "r") as f:
    config = json.load(f)

print(config["host"])
print(config["port"])
print(config["debug"])

#Writing JSON to a File: json.dump

json.dump() (no "s") writes Python data directly into a file. It's like json.dumps(), but instead of returning a string, it writes straight to the file you pass in.

json.dump writes a Python object directly to a file
import json

results = {
    "run": 1,
    "passed": 47,
    "failed": 3,
    "errors": []
}

with open("results.json", "w") as f:
    json.dump(results, f, indent=2)

print("Saved results.json")
Common mistake

loads/dumps vs load/dump — easy to mix up!

The names are almost identical, so beginners often confuse them:

  • `json.loads(string)` — string in, Python object out
  • `json.dumps(object)` — Python object in, string out
  • `json.load(file)` — file in, Python object out
  • `json.dump(object, file)` — Python object in, file out

Memory trick: the ones with an s work with strings. The ones without an s work with files.

#A Real Example: Config File Round-Trip

Here is a practical pattern you will use all the time: load a config, update a value, and save it back.

Load, modify, and save — the classic config round-trip
import json

# Step 1: create an initial config and save it
default_config = {"username": "guest", "volume": 80, "fullscreen": False}

with open("app_config.json", "w") as f:
    json.dump(default_config, f, indent=2)

# Step 2: load it back, update, and save again
with open("app_config.json", "r") as f:
    config = json.load(f)

config["username"] = "alice"
config["fullscreen"] = True

with open("app_config.json", "w") as f:
    json.dump(config, f, indent=2)

print("Config updated!")
print(json.dumps(config, indent=2))
Watch out

JSON only supports certain Python types

Not everything Python can represent will survive the trip to JSON. Types like set, tuple, datetime, and custom class instances are not supported by default.

``python import json json.dumps({1, 2, 3}) # TypeError: Object of type set is not JSON serializable ``

To save a set, convert it to a list first: json.dumps(list(my_set)).

Quick check

You have a variable `text = '{"city": "Paris", "pop": 2161000}'`. Which call correctly converts it into a Python dictionary?

Key takeaways

  • JSON is a universal text format — it maps cleanly to Python dicts, lists, strings, numbers, booleans, and None.
  • Use json.loads() / json.dumps() to convert between JSON strings and Python objects.
  • Use json.load() / json.dump() to read from and write to files directly.
  • Pass indent=2 to json.dumps() or json.dump() to produce readable, pretty-printed JSON.
  • Remember: functions with an 's' work with strings; functions without work with files.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

What does this code print?

predict-output
import json

json_string = '{"city": "Tokyo", "active": true, "count": null}'
data = json.loads(json_string)

print(data["city"])
print(data["active"])
print(data["count"])
Fix the bug#2

This code has a bug. What is wrong?

fix-bug
import json

user = {"name": "Sam", "score": 95}
json_string = json.loads(user)
print(json_string)
Fill in the blank#3

Complete the code so it prints a prettily formatted JSON string with 2-space indentation.

import json

data = {"language": "Python", "level": "beginner"}
result = json.(data, =2)
print(result)
Reorder the lines#4

Put these lines in the right order to convert a JSON string into a Python dict and print one of its values.

1
import json
2
print(data["animal"])
3
text = '{"animal": "cat", "legs": 4}'
4
data = json.loads(text)
Your turn
Practice exercise

Create a Python script that builds a dictionary representing a simple "contact" (with keys: name, email, phone, and a list called 'tags'). Save it to a file called contact.json using json.dump with indent=2. Then load it back, add a new key 'verified' set to True, and print the final JSON to the console using json.dumps with indent=2 and sort_keys=True.

Try it live — edit the code and hit Run to execute real Python:

solution.py · editable