Handling JSON Files
How to work with JSON file in Python.
JSON (JavaScript Object Notation) is a lightweight data format commonly used for APIs, configurations, and data storage.
Python provides the built-in json
module to read, write, and manipulate JSON data.
Before working with JSON, import the json
module:
import json
Reading a JSON File
Use json.load()
to read JSON data from a file.
Let's consider a JSON file for an example: data.json
{
"name": "Jasmeet",
"age": 25,
"city": "New York"
}
Python Code to Read JSON
with open("data.json", "r") as file:
data = json.load(file) # Load JSON as a Python dictionary
print(data) # Output: {'name': 'Jasmeet', 'age': 25, 'city': 'New York'}
Accessing JSON Data
print(data["name"]) # Output: Jasmeet
print(data["age"]) # Output: 25
Writing JSON to a File
Use json.dump()
to write Python objects to a JSON file.
Writing Data to data.json
person = {
"name": "Chris",
"age": 30,
"city": "Los Angeles"
}
with open("data.json", "w") as file:
json.dump(person, file, indent=4) # `indent=4` for pretty formatting
Converting JSON String to Python Object
Use json.loads()
to convert a JSON-formatted string into a Python dictionary.
json_string = '{"name": "Jasmeet", "age": 25, "city": "New York"}'
data = json.loads(json_string)
print(data) # Output: {'name': 'Jasmeet', 'age': 25, 'city': 'New York'}
Converting Python Object to JSON String
Use json.dumps()
to convert a Python dictionary into a JSON-formatted string.
person = {
"name": "Charlie",
"age": 35,
"city": "Chicago"
}
json_data = json.dumps(person, indent=4)
print(json_data)
Working with JSON Arrays
JSON files often contain lists (arrays) of objects.
JSON (people.json
)
[
{"name": "Jasmeet", "age": 25, "city": "New York"},
{"name": "Chris", "age": 30, "city": "Los Angeles"}
]
Reading JSON with Lists
with open("people.json", "r") as file:
data = json.load(file) # Load JSON as a list of dictionaries
for person in data:
print(person["name"]) # Output: Jasmeet, Chris
Writing a List to JSON
people = [
{"name": "Jasmeet", "age": 25, "city": "New York"},
{"name": "Chris", "age": 30, "city": "Los Angeles"}
]
with open("people.json", "w") as file:
json.dump(people, file, indent=4)
Pretty Printing JSON
To print JSON in a readable format:
print(json.dumps(data, indent=4))
Key points
- Use
json.load()
to read JSON from a file. - Use
json.dump()
to write JSON to a file. - Use
json.loads()
to convert JSON string to a dictionary. - Use
json.dumps()
to convert a dictionary to a JSON string.