How to read, write, and manipulate JSON data using Python
JSON (JavaScript Object Notation) is a lightweight data format used for storing and exchanging data. It is widely used in APIs, configuration files, and web applications.
{
"name": "Alice",
"age": 30,
"languages": ["Python", "JavaScript"]
}
Python includes a built‑in json module for working with JSON data.
import json
json_str = '{"name": "Alice", "age": 30}'
data = json.loads(json_str)
print(data["name"]) # Alice
import json
with open("data.json", "r") as file:
data = json.load(file)
print(data)
import json
person = {"name": "Bob", "age": 25}
with open("output.json", "w") as file:
json.dump(person, file)
You can format JSON output to make it easier to read:
print(json.dumps(person, indent=4))
Use json.dumps() to convert Python objects into JSON strings:
data = {"numbers": [1, 2, 3]}
json_text = json.dumps(data)
print(json_text)
JSON supports only basic types (strings, numbers, lists, dicts). To serialize custom objects, you must convert them manually:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
json_text = json.dumps(p.__dict__)
print(json_text)
Now that you can work with JSON, you're ready to explore how to build simple command‑line tools in Lesson 18: Building Simple Command‑Line Tools.
← Back to Lesson Index