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 −


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 −


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 −


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 −


python_json.htm
Advertisements