← Back to Chapters

Python JSON

? Python JSON

? Quick Overview

JSON (JavaScript Object Notation) is a lightweight text format for storing and exchanging data. It is language-independent but uses syntax similar to JavaScript objects. In Python, we use the built-in json module to convert between Python objects and JSON strings, and to read/write JSON files.

? Key Concepts

  • JSON is text – it is always stored and transmitted as a string.
  • Python ↔ JSON mapping – Python dictionaries, lists, strings, numbers, booleans and None map naturally to JSON objects, arrays, strings, numbers, booleans and null.
  • json.dumps() / json.dump() – convert Python objects to JSON (string or file).
  • json.loads() / json.load() – parse JSON (string or file) into Python objects.
  • JSON is commonly used for APIs, configuration files, and data exchange between systems.

? Syntax and Theory

  • JSON keys and string values must use double quotes "like this".
  • JSON supports:
    • Objects: {"key": "value"}
    • Arrays: [1, 2, 3]
    • Numbers, strings, booleans, null
  • Typical workflow in Python:
    • Prepare a Python object (dict, list, etc.).
    • Serialize to JSON using dumps() or dump().
    • Send/store the JSON string (e.g., file, network, database).
    • Read JSON and deserialize using loads() or load().

? Code Examples

? Converting Python to JSON (dumps)

Use json.dumps() to convert a Python object into a JSON-formatted string that you can print, send over a network, or store in a database.

? View Code Example
import json

person = {"name": "Alice", "age": 25, "city": "New York"}
json_data = json.dumps(person)

print(json_data)
# {"name": "Alice", "age": 25, "city": "New York"}

? Converting JSON String to Python (loads)

Use json.loads() to parse a JSON string and get back a Python object (usually a dictionary or list).

? View Code Example
import json

json_string = '{"name": "Bob", "age": 30, "city": "London"}'
person = json.loads(json_string)

print(person["name"])  # Bob

? Working with JSON Files (dump / load)

Use json.dump() and json.load() to write JSON to a file and read JSON from a file.

? View Code Example
import json

# Write JSON to file
data = {"brand": "Ford", "model": "Mustang", "year": 1964}
with open("car.json", "w") as file:
    json.dump(data, file)

# Read JSON from file
with open("car.json", "r") as file:
    loaded_data = json.load(file)

print(loaded_data)

✨ Formatting JSON Output (Pretty Print)

Use the indent and sort_keys arguments of json.dumps() to produce human-readable (pretty-printed) JSON.

? View Code Example
import json

# A simple Python dictionary
person = {"name": "Charlie", "age": 28, "city": "Berlin"}
# Pretty-print JSON with indentation and sorted keys
print(json.dumps(person, indent=4, sort_keys=True))

? Live Output / Explanation

  • Python to JSON: json.dumps(person) returns a string like {"name": "Alice", "age": 25, "city": "New York"}.
  • JSON to Python: After json.loads(json_string), you can access values using dictionary syntax, e.g. person["name"].
  • Files: json.dump(data, file) writes JSON text into car.json, and json.load(file) reads it back as a Python dictionary.
  • Formatting: Using indent=4 prints JSON on multiple lines, and sort_keys=True orders keys alphabetically for easier reading.

? Tips & Best Practices

  • Use json.dumps() for converting Python objects to a JSON string.
  • Use json.dump() when you want to write JSON directly to a file object.
  • Use json.loads() to parse JSON strings into Python objects.
  • Use json.load() to parse JSON from an open file.
  • Add indent and sort_keys to make JSON output more human-readable.
  • Only serialize JSON-serializable data types (dict, list, str, int, float, bool, None).
  • Remember that JSON requires double quotes around keys and string values.

? Try It Yourself

  • Create a Python list of numbers and convert it into a JSON array using json.dumps().
  • Write a Python dictionary to a JSON file, then read it back and print only a specific value.
  • Create a JSON string that stores your favorite movies (title, year, director) and parse it using json.loads().
  • Experiment with indent values (2, 4, 8) and see how the printed JSON changes.
  • Build a small configuration file in JSON (e.g., app settings) and load it in a Python script.

? Common Use Cases

  • Storing application configuration settings.
  • Exchanging data between frontend (JavaScript) and backend (Python) via APIs.
  • Persisting structured data in files for later processing.
  • Interacting with third-party web services that send/receive JSON.