Python json.JSONDecoder.decode() Method
The Python json.JSONDecoder.decode() method is used to decode a JSON-encoded string into a corresponding Python object.
This method is useful when manually parsing JSON data, especially when working with custom deserialization logic.
Syntax
Following is the syntax of the Python json.JSONDecoder.decode() method β
json.JSONDecoder().decode(s)
Parameters
This method accepts a JSON-encoded string as a parameter that needs to be decoded.
Return Value
This method returns a Python object that represents the parsed JSON data.
Example: Basic Usage of decode()
In this example, we use the json.JSONDecoder.decode() method to manually decode a JSON string β
import json
# JSON string
json_string = '{"name": "Alice", "age": 25, "city": "New York"}'
# Create JSONDecoder instance
decoder = json.JSONDecoder()
# Decode JSON string
data = decoder.decode(json_string)
print("Decoded Data:", data)
Following is the output obtained β
Decoded Data: {'name': 'Alice', 'age': 25, 'city': 'New York'}
Example: Using decode() with JSON Arrays
The decode() method can also handle JSON arrays and convert them into Python lists β
import json
# JSON string (array)
json_string = '[{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]'
# Create JSONDecoder instance
decoder = json.JSONDecoder()
# Decode JSON string
data = decoder.decode(json_string)
print("Decoded List:", data)
We get the output as shown below β
Decoded List: [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
Example: Handling Special Constants
The decode() method can also handle special JSON constants such as NaN and Infinity when using the parse_constant parameter β
import json
# Custom function to handle special constants
def parse_constant_custom(value):
return f"Special value: {value}"
# JSON string with special constants
json_string = '{"value1": NaN, "value2": Infinity, "value3": -Infinity}'
# Create JSONDecoder instance with parse_constant
decoder = json.JSONDecoder(parse_constant=parse_constant_custom)
# Decode JSON string
data = decoder.decode(json_string)
print("Parsed Data:", data)
After executing the above code, we get the following output β
Parsed Data: {'value1': 'Special value: NaN', 'value2': 'Special value: Infinity', 'value3': 'Special value: -Infinity'}
Example: Custom Object Conversion
The object_hook parameter allows us to convert JSON objects into custom Python objects while decoding β
import json
# Sample class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Custom function to decode JSON into Person objects
def custom_decoder(obj):
return Person(obj["name"], obj["age"])
# JSON string
json_string = '{"name": "Bob", "age": 30}'
# Create JSONDecoder instance with object_hook
decoder = json.JSONDecoder(object_hook=custom_decoder)
# Decode JSON string
person = decoder.decode(json_string)
print("Decoded Person:", vars(person))
Following is the output of the above code β
Decoded Person: {'name': 'Bob', 'age': 30}
Example: Preserving Key Order
By default, Python dictionaries maintain order in Python 3.7+, but we can explicitly use the object_pairs_hook parameter to load a JSON object while preserving key order β
import json
from collections import OrderedDict
# JSON string
json_string = '{"c": 3, "b": 2, "a": 1}'
# Create JSONDecoder instance with object_pairs_hook
decoder = json.JSONDecoder(object_pairs_hook=OrderedDict)
# Decode JSON string
data = decoder.decode(json_string)
print("Ordered Data:", data)
The result produced is as follows β
Ordered Data: OrderedDict({'c': 3, 'b': 2, 'a': 1})