Python json.JSONEncoder.__str__ Method



The Python json.JSONEncoder.__str__ method returns a human-readable string representation of a JSONEncoder instance. This is useful for debugging and logging, as it provides details about the encoder's configuration in a more user-friendly format.

It helps understand the properties with which an instance of JSONEncoder was created, such as indentation, key sorting, and other settings.

Syntax

Following is the syntax of the Python json.JSONEncoder.__str__ method −

JSONEncoder.__str__()

Parameters

This method does not accept any parameters.

Return Value

This method returns a human-readable string that represents the JSONEncoder instance.

Example: Default JSONEncoder String Representation

In this example, we create a default JSONEncoder instance and print its string representation −

import json

# Create a default JSONEncoder instance
encoder = json.JSONEncoder()

# Print the string representation
print(str(encoder))

Following is the output of the above code −

<json.encoder.JSONEncoder object at 0x7f527d311580>

Example: String Representation of a Custom JSONEncoder

We modify the encoder by setting the ensure_ascii parameter to False and observe the string representation −

import json

# Create a JSONEncoder with custom settings
encoder = json.JSONEncoder(ensure_ascii=False)

# Print the string representation
print(str(encoder))

We get the output as shown below −

<json.encoder.JSONEncoder object at 0x7f8790116030>

Example: Checking Encoder with Indentation

Here, we set the indent parameter to 4 and check the string representation −

import json

# Create a JSONEncoder with indentation
encoder = json.JSONEncoder(indent=4)

# Print the string representation
print(str(encoder))

The result obtained is as follows −

<json.encoder.JSONEncoder object at 0x7f125d7595b0>

Example: String Representation of a Fully Configured Encoder

We configure multiple parameters such as skipkeys, ensure_ascii, and indent, then print its string representation −

import json

# Create a JSONEncoder with multiple configurations
encoder = json.JSONEncoder(skipkeys=True, ensure_ascii=False, indent=2)

# Print the string representation
print(str(encoder))

After executing the above code, we get the following output −

<json.encoder.JSONEncoder object at 0x7f9a2c1be7e0>
python_json.htm
Advertisements