Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python json.JSONEncoder.__str__ Method



The Pythonjson.JSONEncoder.__str__ method returns a human-readable string representation of aJSONEncoder 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 ofJSONEncoder was created, such as indentation, key sorting, and other settings.

Syntax

Following is the syntax of the Pythonjson.JSONEncoder.__str__ method −

JSONEncoder.__str__()

Parameters

This method does not accept any parameters.

Return Value

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

Example: Default JSONEncoder String Representation

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

import json# Create a default JSONEncoder instanceencoder = json.JSONEncoder()# Print the string representationprint(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 theensure_ascii parameter toFalse and observe the string representation −

import json# Create a JSONEncoder with custom settingsencoder = json.JSONEncoder(ensure_ascii=False)# Print the string representationprint(str(encoder))

We get the output as shown below −

<json.encoder.JSONEncoder object at 0x7f8790116030>

Example: Checking Encoder with Indentation

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

import json# Create a JSONEncoder with indentationencoder = json.JSONEncoder(indent=4)# Print the string representationprint(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 asskipkeys,ensure_ascii, andindent, then print its string representation −

import json# Create a JSONEncoder with multiple configurationsencoder = json.JSONEncoder(skipkeys=True, ensure_ascii=False, indent=2)# Print the string representationprint(str(encoder))

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

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

[8]ページ先頭

©2009-2025 Movatter.jp