Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python json.JSONEncoder.__repr__ Method



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

Syntax

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

JSONEncoder.__repr__()

Parameters

This method does not accept any parameters.

Return Value

This method returns a string that represents theJSONEncoder instance, showing its configuration settings.

Example: Default JSONEncoder Representation

In this example, we create a defaultJSONEncoder instance and print its representation using therepr() function −

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

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

Following is the output obtained −

<json.encoder.JSONEncoder object at 0x7f3b16776090>

Example: Representation with Indentation

Here, we configure theindent parameter to 4 spaces and print its representation −

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

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

The result produced is as follows −

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

[8]ページ先頭

©2009-2025 Movatter.jp