Python json.decoder.JSONDecoder.parse_constant Attribute



The Python json.decoder.JSONDecoder.parse_constant attribute is used to specify a custom function for handling special constant values in JSON, such as Infinity, -Infinity, and NaN.

By default, Python converts these values to float('inf'), float('-inf'), and float('nan'). This attribute allows users to replace them with alternative representations like strings or custom values.

Syntax

Following is the syntax of using the parse_constant attribute −

json.decoder.JSONDecoder(parse_constant=function)

Parameter

It is a function that takes a string ('Infinity', '-Infinity', or 'NaN') and returns a custom value.

Return Value

The parse_constant attribute modifies how JSON special constants are parsed, returning user-defined values.

Example: Default Behavior of parse_constant

By default, Python represents JSON constants as floating-point values −

import json

# JSON string with special constants
json_string = '{"positive": Infinity, "negative": -Infinity, "not_a_number": NaN}'

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

# Decode JSON
parsed_data = decoder.decode(json_string)

print("Parsed JSON:", parsed_data)

Following is the output obtained −

Parsed JSON: {'positive': inf, 'negative': -inf, 'not_a_number': nan}

Example: Converting Constants to Strings

You can use the parse_constant attribute to store JSON special constants as strings instead of floating-point numbers −

import json

# Custom function to convert constants to strings
def convert_constant(value):
   return f"Special Value: {value}"

# JSON string with special constants
json_string = '{"positive": Infinity, "negative": -Infinity, "not_a_number": NaN}'

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

# Decode JSON
parsed_data = decoder.decode(json_string)

print("Converted JSON:", parsed_data)

Following is the output of the above code −

Converted JSON: {'positive': 'Special Value: Infinity', 'negative': 'Special Value: -Infinity', 'not_a_number': 'Special Value: NaN'}

Example: Replacing Constants with Custom Values

You can map special constants to fixed numerical values like 9999 or 0 −

import json

# Custom function to replace constants with fixed values
def replace_constants(value):
   mapping = {"Infinity": 9999, "-Infinity": -9999, "NaN": 0}
   return mapping.get(value, value)

# JSON string with special constants
json_string = '{"positive": Infinity, "negative": -Infinity, "not_a_number": NaN}'

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

# Decode JSON
parsed_data = decoder.decode(json_string)

print("Modified JSON:", parsed_data)

We get the output as shown below −

Modified JSON: {'positive': 9999, 'negative': -9999, 'not_a_number': 0}

Example: Raising an Error for Special Constants

You can use the parse_constant attribute to raise an error when encountering Infinity, -Infinity, or NaN in JSON −

import json

# Custom function to raise an error for constants
def reject_constants(value):
   raise ValueError(f"Invalid constant found: {value}")

# JSON string with special constants
json_string = '{"positive": Infinity, "negative": -Infinity, "not_a_number": NaN}'

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

try:
   # Attempt to decode JSON
   parsed_data = decoder.decode(json_string)
   print("Parsed JSON:", parsed_data)
except ValueError as e:
   print("Error:", e)

The result produced is as shown below −

Error: Invalid constant found: Infinity
python_json.htm
Advertisements