Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python json._default_encoder



The Python json._default_encoder attribute refers to the default instance of json.JSONEncoder, which is used internally by the json module for encoding Python objects into JSON strings.

It provides a standard way to encode Python objects into JSON format without needing to manually instantiate a JSONEncoder object.

Syntax

Following is the syntax of using json._default_encoder attribute −

import json

json_string = json._default_encoder.encode(python_object)

Return Value

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

Example: Encoding JSON

The following example demonstrates how to encode a Python dictionary into a JSON string using the json._default_encoder attribute −

import json

# Python dictionary
data = {"name": "Alice", "age": 25, "city": "New York"}

# Encode Python object using _default_encoder
json_string = json._default_encoder.encode(data)

print("Encoded JSON:", json_string)

Following is the output obtained −

Encoded JSON: {"name": "Alice", "age": 25, "city": "New York"}

Example: Encoding Lists

The json._default_encoder attribute can also encode Python lists into JSON arrays −

import json

# Python list
data_list = [10, 20, 30, 40]

# Encode list using _default_encoder
json_string = json._default_encoder.encode(data_list)

print("Encoded JSON Array:", json_string)

Following is the output of the above code −

Encoded JSON Array: [10, 20, 30, 40]

Example: Handling Non-Serializable Objects

If an object is not serializable, the json._default_encoder attribute raises a TypeError

import json
import datetime

# Python object containing a datetime instance
data = {"name": "Alice", "created_at": datetime.datetime.now()}

try:
   # Attempt to encode non-serializable object
   json_string = json._default_encoder.encode(data)
   print("Encoded JSON:", json_string)
except TypeError as e:
   print("Error:", e)

We get the output as shown below −

Error: Object of type datetime is not JSON serializable

Example: Custom Encoding

By subclassing JSONEncoder, we can customize the behavior of json._default_encoder attribute −

import json
import datetime

# Custom JSONEncoder to handle datetime objects
class CustomEncoder(json.JSONEncoder):
   def default(self, obj):
      if isinstance(obj, datetime.datetime):
         return obj.isoformat()  # Convert datetime to ISO format string
      return super().default(obj)

# Override default encoder
json._default_encoder = CustomEncoder()

# Python dictionary with datetime
data = {"name": "Alice", "created_at": datetime.datetime.now()}

# Encode using custom _default_encoder
json_string = json._default_encoder.encode(data)

print("Custom Encoded JSON:", json_string)

Following is the output obtained −

Custom Encoded JSON: {"name": "Alice", "created_at": "2025-02-26T17:50:57.321435"}
python_json.htm
Advertisements