Python20 min read

Python JSON Handling

Learn JSON end to end: dumps vs dump, loads vs load, reading and writing files, and common real-world API patterns.

Michael Brown
July 26, 2025
5.0k233

JSON is the most common data format used by APIs. If you work with web services, you will see JSON daily.

  Important concept:
  - In Python, JSON maps naturally to dictionaries and lists.
  - JSON object → Python dict
  - JSON array → Python list
  
  ## Python object to JSON string
  
  ```python
  import json
  
  person = {
      "name": "Alice",
      "age": 28,
      "city": "Portland"
  }
  
  json_string = json.dumps(person)
  print(json_string)
  ```
  
  Expected output:
  
  ```
  {"name": "Alice", "age": 28, "city": "Portland"}
  ```
  
  ### Pretty print JSON (good for debugging)
  
  ```python
  json_pretty = json.dumps(person, indent=2)
  print(json_pretty)
  ```
  
  Expected output:
  
  ```
  {
    "name": "Alice",
    "age": 28,
    "city": "Portland"
  }
  ```
  
  ## JSON string to Python object
  
  ```python
  import json
  
  json_string = '{"name": "Bob", "age": 30}'
  person = json.loads(json_string)
  
  print(person)
  print(person["name"])
  ```
  
  Expected output:
  
  ```
  {'name': 'Bob', 'age': 30}
  Bob
  ```
  
  ## Read JSON from a file (load)
  
  ```python
  import json
  
  with open("data.json", "r") as file:
      data = json.load(file)
  
  print(data)
  ```
  
  ## Write JSON to a file (dump)
  
  ```python
  import json
  
  data = {
      "users": [
          {"name": "Tom", "city": "Austin"},
          {"name": "Sarah", "city": "Miami"}
      ]
  }
  
  with open("users.json", "w") as file:
      json.dump(data, file, indent=2)
  ```
  
  ## dumps vs dump (simple rule)
  
  - `dumps()` → returns a **string**
  - `dump()` → writes to a **file**
  
  - `loads()` → converts a **string**
  - `load()` → reads from a **file**
  
  ## Graph: JSON flow in real projects
  
  ```mermaid
  flowchart LR
    A[Python dict/list] -->|json.dumps| B[JSON string]
    B -->|send to API| C[Network]
    C -->|receive JSON| D[JSON string]
    D -->|json.loads| E[Python dict/list]
  ```
  
  ## Practical tip: JSON numbers, booleans, null
  
  - JSON `true/false` → Python `True/False`
  - JSON `null` → Python `None`
  
  If you see `None`, that often means “missing” or “no value”.
  
  In the next lesson, you will learn datetime, because handling dates correctly is a real-world skill in APIs, databases, and logs.
#Python#Intermediate#JSON