Ravindra BagaleCourses & study guides मराठी Track your progress

How to Read and Write CSV, JSON and Text Files in Python (with open and with)

P9.5 How to Read and Write JSON Files in Python

Why. APIs and apps send data as JSON. It looks exactly like Python dictionaries and lists.

What. json.load(f) reads a JSON file into Python. json.dump(data, f) writes Python data as JSON. json.loads(text) / json.dumps(data) work with strings.

How.

Work with JSON

  1. Open the file with utf-8.
  2. Use json.load to read.
  3. Access values like dicts and lists.
  4. Use json.dump(data, f, indent=2) to write a readable file.

Worked example A — Read a JSON file.

Step 1 — What we do. An e-commerce app in Spain exports orders as JSON.

Step 2 — Make the input file orders.json in the same folder as your code:

{"shop": "Madrid Central", "currency": "EUR", "orders": [{"id": "M1", "total": 35.5}, {"id": "M2", "total": 12.0}]}

About this data: the file has the shop name, the currency, and a list of orders. Each order has an id and a total in euros.

Step 3 — Type and run this code.

import json
with open("orders.json", encoding="utf-8") as f:
    data = json.load(f)
print(data["shop"])
for o in data["orders"]:
    print(o["id"], o["total"])

Step 4 — Output you should see.

Madrid Central
M1 35.5
M2 12.0

Step 5 — What it means. JSON objects become dicts and arrays become lists.

Worked example B — Write JSON.

Step 1 — What we do. We save a settings dictionary for a report.

Step 2 — Type and run this code.

import json
settings = {"region": "EU", "currency": "€", "top_n": 5}
with open("settings.json", "w", encoding="utf-8") as f:
    json.dump(settings, f, indent=2, ensure_ascii=False)
print(open("settings.json", encoding="utf-8").read())

Step 3 — Output you should see.

{
  "region": "EU",
  "currency": "€",
  "top_n": 5
}

Step 4 — What it means. indent=2 makes it readable. ensure_ascii=False keeps € as €, not \u20ac.

Python JSON
dict object { }
list array [ ]
str string
int / float number
True / False true / false
None null

How to read this table: each row shows a Python type and what it becomes in JSON.

Ravindra Bagale's Tip

If an API gives nested JSON, look at one record first with print(json.dumps(rec, indent=2)). Then decide which fields you need.