Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python json.JSONEncoder.encode() Method



The Pythonjson.JSONEncoder.encode() method is a method of thejson.JSONEncoder class that directly encodes a Python object into a JSON-formatted string.

Unlikejson.dumps(), which is a higher-level function,encode() provides lower-level control over the serialization process. It is typically used when customizing the behavior of JSON encoding in a subclass ofJSONEncoder.

Syntax

Following is the syntax of the Pythonjson.JSONEncoder.encode() method −

json.JSONEncoder().encode(obj)

Parameters

This method accepts the Python object as a parameter that needs to be serialized into a JSON-formatted string.

Return Value

This method returns a JSON-formatted string representation of the given Python object.

Example: Basic Usage of encode()

Theencode() method can be used to convert basic Python objects into JSON-formatted strings −

import json# Create an instance of JSONEncoderencoder = json.JSONEncoder()# Sample dictionarydata = {"name": "Alice", "age": 25, "city": "London"}# Convert dictionary to JSON stringjson_string = encoder.encode(data)print("JSON Output:", json_string)

Following is the output obtained −

JSON Output: {"name": "Alice", "age": 25, "city": "London"}

Example: Custom JSON Encoding

We can subclassjson.JSONEncoder to customize the encoding process and override theencode() method −

import json# Custom JSON Encoderclass CustomEncoder(json.JSONEncoder):   def encode(self, obj):      # Add a custom message before encoding      json_str = super().encode(obj)      return f"CustomEncoded: {json_str}"# Create an object of CustomEncoderencoder = CustomEncoder()# Sample dictionarydata = {"name": "Bob", "age": 30, "city": "New York"}# Serialize using custom encoderjson_string = encoder.encode(data)print("Custom JSON Output:", json_string)

We get the output as shown below −

Custom JSON Output: CustomEncoded: {"name": "Bob", "age": 30, "city": "New York"}

Example: Encoding a Custom Object

By default,json.JSONEncoder.encode() does not support encoding custom Python objects. We can override thedefault() method to enable custom object encoding −

import json# Custom classclass Person:   def __init__(self, name, age):      self.name = name      self.age = age# Custom JSON Encoderclass PersonEncoder(json.JSONEncoder):   def default(self, obj):      if isinstance(obj, Person):         return {"name": obj.name, "age": obj.age}      return super().default(obj)# Create an object of Person classperson = Person("Charlie", 40)# Create an encoder instanceencoder = PersonEncoder()# Serialize object using encode()json_string = encoder.encode(person)print("JSON Output:", json_string)

The result produced is as shown below −

JSON Output: {"name": "Charlie", "age": 40}

Example: Pretty-Printing JSON

We can use theindent parameter injson.JSONEncoder to format the JSON output for better readability −

import json# Create an instance of JSONEncoder with indentationencoder = json.JSONEncoder(indent=4)# Sample dictionarydata = {"name": "Alice", "age": 25, "city": "London"}# Convert dictionary to formatted JSON stringjson_string = encoder.encode(data)print("Pretty-Printed JSON Output:")print(json_string)

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

Pretty-Printed JSON Output:{    "name": "Alice",    "age": 25,    "city": "London"}

Example: Using separators Parameter

Theseparators parameter allows customization of JSON formatting −

import json# Create an instance of JSONEncoder with custom separatorsencoder = json.JSONEncoder(separators=(",", ":"))# Sample dictionarydata = {"name": "Alice", "age": 25, "city": "London"}# Convert dictionary to JSON with custom separatorsjson_string = encoder.encode(data)print("Compact JSON Output:", json_string)

Following is the output obtained −

Compact JSON Output: {"name":"Alice","age":25,"city":"London"}
python_json.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp