๐Python JSON: Encode (dumps), Decode (loads) & Read JSON Files
Python JSON: JSON (JavaScript Object Notation) is a widely used data format for data exchange between systems. In Python, JSON handling is efficient with the built-in json module. This guide explains Python JSON operations such as encoding, decoding, and reading JSON files with practical examples.
๐What is Python JSON?
JSON is a text format inspired by JavaScript that is commonly used for data exchange. It represents data as key-value pairs, similar to Python dictionaries. JSON can be used in APIs, databases, and web services.
๐ Python JSON Syntax Example:
json
{
“name”: “John”,
“age”: 30,
“married”: true
}
๐JSON Library in Python
To work with JSON in Python, import the json module:
python
import json
๐Key Methods in Python JSON Module:
- dumps() โ Encodes Python objects to JSON strings
- dump() โ Writes encoded JSON data to a file
- loads() โ Decodes JSON strings into Python objects
- load() โ Reads JSON data from a file and decodes it
๐Python to JSON Encoding (Using dumps())
Python objects can be converted into JSON format using the dumps() method.
๐Example:
python
import json
data = {
“name”: “Alice”,
“age”: 28,
“hobbies”: [“reading”, “gaming”],
“is_active”: True
}
json_data = json.dumps(data, indent=4, sort_keys=True)
print(json_data)
๐Output:
json
{
“age”: 28,
“hobbies”: [
“reading”,
“gaming”
],
“is_active”: true,
“name”: “Alice”
}
๐Writing JSON Data to a File (Using dump())
To save JSON data into a file, use the dump() method.
๐Example:
python
import json
data = {“name”: “Bob”, “age”: 35}
with open(‘data.json’, ‘w’) as file:
json.dump(data, file, indent=4)
This creates a file named data.json with the given data.
๐JSON to Python Decoding (Using loads() and load())
To decode JSON data into Python objects, use loads() for JSON strings and load() for JSON files.
๐Example with loads()
python
import json
json_string = ‘{“name”: “Ken”, “age”: 28, “is_married”: false}’
data = json.loads(json_string)
print(data)
๐Output:
python
{‘name’: ‘Ken’, ‘age’: 28, ‘is_married’: False}
๐Reading JSON Files in Python (Using load())
To read JSON data directly from a file:
๐Example:
python
import json
with open(‘data.json’) as file:
data = json.load(file)
print(data)
๐Compact Encoding in JSON
For space-efficient JSON output, use the separators parameter.
๐Example:
python
import json
data = [‘a’, ‘b’, ‘c’, {‘x’: 5, ‘y’: 10}]
compact_data = json.dumps(data, separators=(‘,’, ‘:’))
print(compact_data)
๐Output: [“a”,”b”,”c”,{“x”:5,”y”:10}]
๐Pretty Printing JSON in Python
For well-structured JSON output, use the indent parameter in dumps().
๐Example:
python
import json
data = {“a”: 4, “b”: 5}
formatted_json = json.dumps(data, indent=4)
print(formatted_json)
๐Output:
json
{
“a”: 4,
“b”: 5
}
๐Sorting JSON Data (Using sort_keys=True)
To display JSON keys in alphabetical order:
๐Example:
python
import json
data = {
“z”: 3,
“a”: 1,
“m”: 2
}
sorted_json = json.dumps(data, indent=4, sort_keys=True)
print(sorted_json)
๐Output:
json
{
“a”: 1,
“m”: 2,
“z”: 3
}
๐Encoding Complex Objects in JSON
For complex objects like complex numbers, you need a custom encoding function.
๐Example:
python
import json
def encode_complex(obj):
if isinstance(obj, complex):
return [obj.real, obj.imag]
raise TypeError(“Object is not JSON serializable”)
complex_num = json.dumps(4 + 5j, default=encode_complex)
print(complex_num)
Output: [4.0, 5.0]
๐Decoding Complex JSON Data
For decoding complex JSON data, use the object_hook parameter.
๐Example:
python
import json
def decode_complex(obj):
if ‘__complex__’ in obj:
return complex(obj[‘real’], obj[‘img’])
return obj
json_data = ‘{“__complex__”: true, “real”: 4, “img”: 5}’
complex_object = json.loads(json_data, object_hook=decode_complex)
print(complex_object)
๐Output: (4+5j)
๐JSONEncoder and JSONDecoder in Python
- JSONEncoder encodes Python objects to JSON strings.
- JSONDecoder decodes JSON strings into Python objects.
๐Encoder Example:
python
from json.encoder import JSONEncoder
data = {“colors”: [“red”, “green”, “blue”]}
encoded_data = JSONEncoder().encode(data)
print(encoded_data)
๐Output: ‘{“colors”: [“red”, “green”, “blue”]}’
๐Decoder Example:
python
from json.decoder import JSONDecoder
json_str = ‘{“name”: “Alice”, “age”: 30}’
decoded_data = JSONDecoder().decode(json_str)
print(decoded_data)
๐Output: {‘name’: ‘Alice’, ‘age’: 30}
๐Common JSON Errors in Python
While handling JSON data, common errors include:
- JSONDecodeError โ Incorrect JSON format
- TypeError โ Unsupported object type for encoding
๐Example Handling JSONDecodeError:
python
import json
try:
with open(‘invalid_file.json’) as file:
data = json.load(file)
except json.JSONDecodeError:
print(“Invalid JSON format!”)
