Python json.JSONEncoder Class



The Python json.JSONEncoder class is used to customize how Python objects are serialized into JSON format.

By default, Python's json.dumps() function converts basic data types like dictionaries, lists, and strings into JSON. However, we can subclass json.JSONEncoder to define custom serialization logic for complex objects.

Syntax

Following is the syntax of the Python json.JSONEncoder class βˆ’

class json.JSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Parameters

This class accepts the following parameters βˆ’

  • skipkeys (optional): If True, non-string dictionary keys are ignored.
  • ensure_ascii (optional): If True, all non-ASCII characters are escaped.
  • check_circular (optional): If True, circular references are checked.
  • allow_nan (optional): If True, NaN, Infinity, and -Infinity are allowed.
  • sort_keys (optional): If True, dictionary keys are sorted in the output.
  • indent (optional): Specifies indentation level for pretty-printing.
  • separators (optional): Defines custom separators for key-value pairs.
  • default (optional): A function used to serialize unsupported objects.

Return Value

This class returns an encoder object that can be used to serialize Python objects into JSON format.

Example: Using Default JSON Encoding

By default, json.dumps() automatically encodes basic Python objects into JSON βˆ’

import json

# Sample dictionary
data = {"name": "Alice", "age": 25, "city": "London"}

# Convert dictionary to JSON string
json_string = json.dumps(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 define a custom encoding function for complex objects by subclassing json.JSONEncoder βˆ’

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("John Doe", 35)

# Serialize object using custom encoder
json_string = json.dumps(person, cls=PersonEncoder)

print("JSON Output:", json_string)

We get the output as shown below βˆ’

JSON Output: {"name": "John Doe", "age": 35}

Example: Using the default Parameter

The default parameter in json.dumps() allows us to specify a function for encoding unsupported types βˆ’

import json

# Custom class
class Car:
   def __init__(self, brand, year):
      self.brand = brand
      self.year = year

# Custom function to serialize Car objects
def encode_car(obj):
   if isinstance(obj, Car):
      return {"brand": obj.brand, "year": obj.year}
   raise TypeError(f"Object of type {obj.__class__.__name__} is not JSON serializable")

# Create an object of Car class
car = Car("Toyota", 2022)

# Serialize object using default parameter
json_string = json.dumps(car, default=encode_car)

print("JSON Output:", json_string)

The result produced is as follows βˆ’

JSON Output: {"brand": "Toyota", "year": 2022}

Example: Sorting Keys

The sort_keys parameter ensures that keys are sorted in ascending order when converting a dictionary to JSON βˆ’

import json

# Sample dictionary
data = {"b": 2, "a": 1, "c": 3}

# Convert dictionary to JSON with sorted keys
json_string = json.dumps(data, sort_keys=True)

print("JSON Output:", json_string)

After executing the above code, we get the following output βˆ’

JSON Output: {"a": 1, "b": 2, "c": 3}

Example: Pretty-Printing JSON

The indent parameter allows us to format JSON output with proper indentation βˆ’

import json

# Sample dictionary
data = {"name": "Alice", "age": 25, "city": "London"}

# Convert dictionary to JSON with indentation
json_string = json.dumps(data, indent=4)

print("JSON Output:")
print(json_string)

Following is the output of the above code βˆ’

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

Example: Using separators Parameter

The separators parameter controls the formatting of key-value pairs in JSON βˆ’

import json

# Sample dictionary
data = {"name": "Alice", "age": 25, "city": "London"}

# Convert dictionary to JSON with custom separators
json_string = json.dumps(data, separators=(",", ":"))

print("JSON Output:", json_string)

The result obtained is as follows βˆ’

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