JSON (JavaScript Object Notation) is the de facto standard for data exchange on the web. Python's built-in `json` module provides an easy and efficient way to work with JSON data.
From Python Dictionary to JSON String (`json.dumps`)
The `json.dumps()` function (dump string) converts a Python dictionary into a JSON formatted string.
import json
# A Python dictionary
user_data = {
"id": 101,
"name": "Alice",
"isAdmin": True,
"courses": ["History", "Math"]
}
# Convert dictionary to JSON string
# Use indent for pretty-printing
json_string = json.dumps(user_data, indent=4)
print(json_string)
From JSON String to Python Dictionary (`json.loads`)
The `json.loads()` function (load string) parses a JSON string and converts it back into a Python dictionary.
import json
json_data = '{"name": "Bob", "age": 30, "city": "New York"}'
# Convert JSON string to Python dictionary
python_dict = json.loads(json_data)
print(python_dict)
print(f'Name: {python_dict["name"]}')
Reading and Writing JSON files
You can combine the `json` module with file I/O operations to work directly with `.json` files.
import json
# Writing to a file
with open('user.json', 'w') as f:
json.dump(user_data, f, indent=4) # Note: json.dump (no 's')
# Reading from a file
with open('user.json', 'r') as f:
loaded_data = json.load(f) # Note: json.load (no 's')
print(f'Loaded user: {loaded_data["name"]}')
Comments
Post a Comment