Python json.JSONEncoder.encode() Method



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

Unlike json.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 of JSONEncoder.

Syntax

Following is the syntax of the Python json.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()

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

Open Compiler
import json # Create an instance of JSONEncoder encoder = json.JSONEncoder() # Sample dictionary data = {"name": "Alice", "age": 25, "city": "London"} # Convert dictionary to JSON string json_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 subclass json.JSONEncoder to customize the encoding process and override the encode() method −

Open Compiler
import json # Custom JSON Encoder class 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 CustomEncoder encoder = CustomEncoder() # Sample dictionary data = {"name": "Bob", "age": 30, "city": "New York"} # Serialize using custom encoder json_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 the default() method to enable custom object encoding −

Open Compiler
import json # Custom class class Person: def __init__(self, name, age): self.name = name self.age = age # Custom JSON Encoder class 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 class person = Person("Charlie", 40) # Create an encoder instance encoder = 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 the indent parameter in json.JSONEncoder to format the JSON output for better readability −

Open Compiler
import json # Create an instance of JSONEncoder with indentation encoder = json.JSONEncoder(indent=4) # Sample dictionary data = {"name": "Alice", "age": 25, "city": "London"} # Convert dictionary to formatted JSON string json_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

The separators parameter allows customization of JSON formatting −

Open Compiler
import json # Create an instance of JSONEncoder with custom separators encoder = json.JSONEncoder(separators=(",", ":")) # Sample dictionary data = {"name": "Alice", "age": 25, "city": "London"} # Convert dictionary to JSON with custom separators json_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
Advertisements