Python JSON Module
Learn Python through interactive, bite-sized lessons. Practice with real code challenges and build projects step-by-step.
Start Python Journey →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.
What is JSON?
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.
Importing the JSON Module
To use the JSON module, you need to import it first:
import json
Encoding Python Objects to 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)
Decoding JSON to Python Objects
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
Working with JSON Files
The JSON module also provides methods for reading from and writing to JSON files:
Writing to a JSON File
data = {"employees": [{"name": "Alice", "role": "Developer"}, {"name": "Bob", "role": "Manager"}]}
with open("data.json", "w") as file:
json.dump(data, file)
Reading from a JSON File
with open("data.json", "r") as file:
loaded_data = json.load(file)
print(loaded_data)
Important Considerations
- JSON only supports a limited set of data types: strings, numbers, booleans, null, arrays, and objects.
- Python-specific types like
datetimeobjects need to be converted before encoding to JSON. - Use the
indentparameter injson.dumps()for pretty-printing JSON output.
Related Concepts
To further enhance your Python skills, explore these related topics:
- Python File Open and Close for working with files
- Python Dictionaries for understanding JSON-like data structures in Python
- Python Requests Library for working with web APIs that often use JSON
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.