Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python json.decoder.JSONDecoder.parse_constant Attribute



The Pythonjson.decoder.JSONDecoder.parse_constant attribute is used to specify a custom function for handling special constant values in JSON, such asInfinity,-Infinity, andNaN.

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

Syntax

Following is the syntax of using theparse_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

Theparse_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 constantsjson_string = '{"positive": Infinity, "negative": -Infinity, "not_a_number": NaN}'# Create JSONDecoder instance with default parse_constantdecoder = json.decoder.JSONDecoder()# Decode JSONparsed_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 theparse_constant attribute to store JSON special constants as strings instead of floating-point numbers −

import json# Custom function to convert constants to stringsdef convert_constant(value):   return f"Special Value: {value}"# JSON string with special constantsjson_string = '{"positive": Infinity, "negative": -Infinity, "not_a_number": NaN}'# Create JSONDecoder instance with custom parse_constantdecoder = json.decoder.JSONDecoder(parse_constant=convert_constant)# Decode JSONparsed_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 valuesdef replace_constants(value):   mapping = {"Infinity": 9999, "-Infinity": -9999, "NaN": 0}   return mapping.get(value, value)# JSON string with special constantsjson_string = '{"positive": Infinity, "negative": -Infinity, "not_a_number": NaN}'# Create JSONDecoder instance with replace_constants functiondecoder = json.decoder.JSONDecoder(parse_constant=replace_constants)# Decode JSONparsed_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 theparse_constant attribute to raise an error when encounteringInfinity,-Infinity, orNaN in JSON −

import json# Custom function to raise an error for constantsdef reject_constants(value):   raise ValueError(f"Invalid constant found: {value}")# JSON string with special constantsjson_string = '{"positive": Infinity, "negative": -Infinity, "not_a_number": NaN}'# Create JSONDecoder instance with reject_constants functiondecoder = 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
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp