Python Read/Write JSON

JSON in Python

JSON (JavaScript Object Notation) is used for storing and exchanging data, commonly in APIs and configuration files.

Python has a built-in module:

import json

Write (Save) JSON to a File

Example Dictionary/Data

data = {
    "name": "Deepesh",
    "age": 30,
    "skills": ["Python", "Selenium", "Automation"]
}

Save to JSON file

import json

with open("data.json", "w") as file:
    json.dump(data, file, indent=4)

indent=4 makes the JSON formatted & readable.


Read (Load) JSON from a File

import json

with open("data.json", "r") as file:
    content = json.load(file)
    print(content)

Output

{'name': 'Deepesh', 'age': 30, 'skills': ['Python', 'Selenium', 'Automation']}

Now content is a Python dictionary, and you can access elements like:

print(content["name"])
print(content["skills"][1])

Convert Python Data ↔ JSON String

Convert Python → JSON string

import json

person = {"city": "Delhi", "pin": 110001}
json_string = json.dumps(person)
print(json_string)

Convert JSON string → Python


Update JSON File

import json

# Read existing content
with open("data.json", "r") as file:
    data = json.load(file)

# Modify data
data["age"] = 31
data["skills"].append("API Testing")

# Write back to file
with open("data.json", "w") as file:
    json.dump(data, file, indent=4)

Work with Lists in JSON

Example JSON file (employees.json)

[
    {"id": 1, "name": "Ankit"},
    {"id": 2, "name": "Riya"}
]

Add a new record

import json

with open("employees.json", "r") as file:
    employees = json.load(file)

employees.append({"id": 3, "name": "Aman"})

with open("employees.json", "w") as file:
    json.dump(employees, file, indent=4)

Summary

TaskFunction
Write Python → JSON filejson.dump()
Read JSON file → Pythonjson.load()
Python → JSON stringjson.dumps()
JSON string → Pythonjson.loads()

Leave a Comment