Python json.JSONEncoder.__repr__ Method
The Python json.JSONEncoder.__repr__ method returns a string representation of a JSONEncoder instance. This is useful for debugging and logging, as it provides details about the encoder's configuration.
It helps in understanding the properties with which an instance of JSONEncoder was created, such as indentation, key sorting, and other parameters.
Syntax
Following is the syntax of the Python json.JSONEncoder.__repr__ method −
JSONEncoder.__repr__()
Parameters
This method does not accept any parameters.
Return Value
This method returns a string that represents the JSONEncoder instance, showing its configuration settings.
Example: Default JSONEncoder Representation
In this example, we create a default JSONEncoder instance and print its representation using the repr() function −
import json # Create a default JSONEncoder instance encoder = json.JSONEncoder() # Print the representation print(repr(encoder))
Following is the output of the above code −
<json.encoder.JSONEncoder object at 0x7fe83c4f1580>
Example: Using Custom Parameters
We modify the encoder by setting the ensure_ascii parameter to False and check the string representation −
import json # Create a JSONEncoder with custom settings encoder = json.JSONEncoder(ensure_ascii=False) # Print the representation print(repr(encoder))
Following is the output obtained −
<json.encoder.JSONEncoder object at 0x7f3b16776090>
Example: Representation with Indentation
Here, we configure the indent parameter to 4 spaces and print its representation −
import json # Create a JSONEncoder with indentation encoder = json.JSONEncoder(indent=4) # Print the representation print(repr(encoder))
We get the output as shown below −
<json.encoder.JSONEncoder object at 0x7fa0d97b15b0>
Example: Representation of Fully Configured Encoder
We configure multiple parameters such as skipkeys, ensure_ascii, and indent, then print its representation −
import json # Create a JSONEncoder with multiple configurations encoder = json.JSONEncoder(skipkeys=True, ensure_ascii=False, indent=2) # Print the representation print(repr(encoder))
The result produced is as follows −
<json.encoder.JSONEncoder object at 0x7f3fb2ec67e0>
python_json.htm