TracksPractical Coding FoundationsWorking With FilesWorking With JSON Files(6 of 9)

Working With JSON Files

JSON (JavaScript Object Notation) is everywhere in modern software. APIs return it, configuration files use it, and data gets stored in it. Understanding JSON is essential for any developer.

JSON Structure

JSON looks remarkably like Python dictionaries and lists:

{
  "name": "Alice",
  "age": 30,
  "active": true,
  "skills": ["Python", "JavaScript"],
  "address": {
    "city": "New York",
    "zip": "10001"
  }
}

JSON supports:

  • Objects (like dictionaries): {"key": "value"}
  • Arrays (like lists): [1, 2, 3]
  • Strings: "hello"
  • Numbers: 42, 3.14
  • Booleans: true, false
  • Null: null

Note: JSON uses true/false (lowercase), while Python uses True/False.

Reading JSON Files

Python's json module converts JSON files into Python objects:

import json

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

print(data["name"])        # Alice
print(data["skills"][0])   # Python
print(data["address"]["city"])  # New York

The json.load() function reads the file and returns a dictionary (or list, depending on the JSON structure).

Writing JSON Files

To save Python data as JSON:

import json

config = {
    "debug": True,
    "database": "myapp.db",
    "port": 3000,
    "allowed_hosts": ["localhost", "myapp.com"]
}

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

The indent=2 parameter formats the output with nice indentation, making it human-readable. Without it, everything appears on one line.

Common Configuration Pattern

Many applications use JSON for settings:

{
  "app_name": "MyApp",
  "debug": false,
  "database": {
    "host": "localhost",
    "port": 5432,
    "name": "myapp_db"
  },
  "features": {
    "dark_mode": true,
    "notifications": false
  }
}

Your program reads this at startup and uses the values throughout.

Also Know: YAML

YAML is another popular configuration format, especially in DevOps tools like Docker and CI/CD pipelines. It's more human-readable but requires an external library:

app_name: MyApp
debug: false
database:
  host: localhost
  port: 5432

You'll encounter YAML in configuration files, but JSON remains the standard for data exchange.

See More

Further Reading

You need to be signed in to leave a comment and join the discussion