JSON (JavaScript Object Notation) is a popular data interchange format that is widely used for data storage and transmission. Python provides built-in support for working with JSON data through the json
module.
Let’s explore working with JSON in Python:
import json
# Converting Python objects to JSON
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
json_data = json.dumps(person)
print(json_data)
# Writing JSON to a file
with open("person.json", "w") as file:
json.dump(person, file)
# Reading JSON from a file
with open("person.json", "r") as file:
json_data = json.load(file)
print(json_data)
# Converting JSON to Python objects
person = json.loads(json_data)
print(person)
# Pretty-printing JSON
json_data = json.dumps(person, indent=4)
print(json_data)
# Handling JSON with nested objects
data = {
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY"
}
}
json_data = json.dumps(data, indent=4)
print(json_data)
# Accessing nested data
city = data["address"]["city"]
print(city)
Explanation:
- The
json.dumps()
function is used to convert Python objects to JSON-formatted strings. - The
json.dump()
function is used to write JSON data to a file. - The
json.load()
function is used to read JSON data from a file. - The
json.loads()
function is used to convert JSON strings to Python objects. - The
indent
parameter is used to specify the indentation level for pretty-printing JSON. - JSON data can contain nested objects, and you can access nested data using indexing.
Now it’s time for a practical task:
Task 21:
Create a Python dictionary representing a book with attributes such as title, author, and publication year. Convert the dictionary to JSON and write it to a file called “book.json”. Then, read the JSON data from the file, convert it back to a Python object, and print the book details.
Once you’ve completed the task, you can proceed to the next lesson.