The JSON module in Python provides a simple way to encode and decode JSON data. It's an essential tool for working with web APIs and storing structured data.
JSON (JavaScript Object Notation) is a lightweight data interchange format. It's easy for humans to read and write, and simple for machines to parse and generate.
To use the JSON module, you need to import it first:
import json
Use the json.dumps()
method to convert Python objects into JSON strings:
data = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
json_string = json.dumps(data)
print(json_string)
The json.loads()
method parses a JSON string and returns a Python object:
json_string = '{"name": "Jane Smith", "age": 25, "city": "London"}'
python_obj = json.loads(json_string)
print(python_obj["name"]) # Output: Jane Smith
The JSON module also provides methods for reading from and writing to JSON files:
data = {"employees": [{"name": "Alice", "role": "Developer"}, {"name": "Bob", "role": "Manager"}]}
with open("data.json", "w") as file:
json.dump(data, file)
with open("data.json", "r") as file:
loaded_data = json.load(file)
print(loaded_data)
datetime
objects need to be converted before encoding to JSON.indent
parameter in json.dumps()
for pretty-printing JSON output.To further enhance your Python skills, explore these related topics:
Mastering the JSON module is crucial for modern Python development, especially when dealing with web services and data interchange. Practice encoding and decoding various data structures to become proficient in handling JSON in Python.