
👉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!”)