Selected Reading

Python json.decoder.JSONDecoder Class



The Python json.decoder.JSONDecoder class is used to deserialize JSON-encoded strings into Python objects.

This class is useful when parsing JSON data received from APIs, files, or user inputs into native Python data structures.

Syntax

Following is the syntax of the Python json.decoder.JSONDecoder class −

json.decoder.JSONDecoder(
   object_hook=None, 
   parse_float=None, 
   parse_int=None, 
   parse_constant=None, 
   strict=True
)

Parameters

This function accepts the following parameters −

  • object_hook (optional): A function that can be used to convert dictionary objects into custom objects.
  • parse_float (optional): A function used to parse floating-point numbers.
  • parse_int (optional): A function used to parse integers.
  • parse_constant (optional): A function used to handle special JSON values (e.g., NaN, Infinity).
  • strict (optional): If True (default), raises errors for malformed JSON input.

Return Value

This class returns a JSONDecoder object that can be used to parse JSON strings into Python objects.

Example: Basic JSON Decoding

In this example, we use the JSONDecoder class to parse a JSON string −

import json

# Define JSON string
json_string = '{"name": "Alice", "age": 25, "city": "London"}'

# Create JSONDecoder instance
decoder = json.decoder.JSONDecoder()

# Decode JSON string into a Python dictionary
parsed_data = decoder.decode(json_string)

print("Decoded JSON:", parsed_data)

Following is the output obtained −

Decoded JSON: {'name': 'Alice', 'age': 25, 'city': 'London'}

Example: Custom Decoding

The object_hook parameter allows transforming JSON objects into custom Python objects −

import json

# Define a custom object class
class Person:
   def __init__(self, name, age, city):
      self.name = name
      self.age = age
      self.city = city

   def __repr__(self):
      return f"Person(name={self.name}, age={self.age}, city={self.city})"

# Custom decoding function
def custom_decoder(obj):
   return Person(obj['name'], obj['age'], obj['city'])

# JSON string
json_string = '{"name": "Bob", "age": 40, "city": "Paris"}'

# Create JSONDecoder instance with object_hook
decoder = json.decoder.JSONDecoder(object_hook=custom_decoder)

# Decode JSON string into a custom object
parsed_data = decoder.decode(json_string)

print("Decoded Custom Object:", parsed_data)

Following is the output of the above code −

Decoded Custom Object: Person(name=Bob, age=40, city=Paris)

Example: Handling Special JSON Values

The parse_constant parameter can be used to handle special JSON constants like NaN, Infinity −

import json

# Custom function to handle special JSON constants
def handle_constants(value):
   return f"Special value: {value}"

# JSON string with NaN and Infinity
json_string = '{"value1": NaN, "value2": Infinity}'

# Create JSONDecoder instance with parse_constant
decoder = json.decoder.JSONDecoder(parse_constant=handle_constants)

# Decode JSON string
parsed_data = decoder.decode(json_string)

print("Decoded JSON with Special Constants:", parsed_data)

We get the output as shown below −

Decoded JSON with Special Constants: {'value1': 'Special value: NaN', 'value2': 'Special value: Infinity'}

Example: Custom Parsing of Numbers

The parse_int and parse_float parameters can be used to modify the way numbers are parsed −

import json

# Custom function to handle integers
def parse_int(value):
   return f"Integer({value})"

# Custom function to handle floats
def parse_float(value):
   return f"Float({value})"

# JSON string with numbers
json_string = '{"count": 5, "price": 19.99}'

# Create JSONDecoder instance with custom parsing functions
decoder = json.decoder.JSONDecoder(parse_int=parse_int, parse_float=parse_float)

# Decode JSON string
parsed_data = decoder.decode(json_string)

print("Decoded JSON with Custom Number Parsing:", parsed_data)

The result produced is as follows −

Decoded JSON with Custom Number Parsing: {'count': 'Integer(5)', 'price': 'Float(19.99)'}
python_json.htm
Advertisements