The json Module
Reference: https://docs.python.org/3/library/json.html.
Usage
Writing JSON
Use json.dumps() to convert a dictionary to a JSON-formatted string:
import json
person = {
"first_name": "Ophelia",
"last_name": "Clarke",
"message": "Hi, thanks for the ice cream!",
"fav_flavors": ["Vanilla Bean", "Mocha", "Strawberry"]
}
raw_data = json.dumps(person)
print(type(raw_data)) #> <class 'str'>
print(raw_data) #> '{"first_name": "Ophelia", "last_name": "Clarke", "message": "Hi, thanks for the ice cream!", "fav_flavors": ["Vanilla Bean", "Mocha", "Strawberry"]}'Reading JSON
Use json.loads() to convert a JSON-formatted string into a Python dictionary.
Reading and Writing JSON Files
Combine these JSON-parsing techniques with file management techniques to read and write JSON data from a .json file.
Writing:
Reading:
Last updated
Was this helpful?