Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python json.JSONEncoder Class



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

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

Syntax

Following is the syntax of the Pythonjson.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): IfTrue, non-string dictionary keys are ignored.
  • ensure_ascii (optional): IfTrue, all non-ASCII characters are escaped.
  • check_circular (optional): IfTrue, circular references are checked.
  • allow_nan (optional): IfTrue, NaN, Infinity, and -Infinity are allowed.
  • sort_keys (optional): IfTrue, 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 dictionarydata = {"name": "Alice", "age": 25, "city": "London"}# Convert dictionary to JSON stringjson_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 subclassingjson.JSONEncoder

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("John Doe", 35)# Serialize object using custom encoderjson_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

Thedefault parameter injson.dumps() allows us to specify a function for encoding unsupported types −

import json# Custom classclass Car:   def __init__(self, brand, year):      self.brand = brand      self.year = year# Custom function to serialize Car objectsdef 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 classcar = Car("Toyota", 2022)# Serialize object using default parameterjson_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

Thesort_keys parameter ensures that keys are sorted in ascending order when converting a dictionary to JSON −

import json# Sample dictionarydata = {"b": 2, "a": 1, "c": 3}# Convert dictionary to JSON with sorted keysjson_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

Theindent parameter allows us to format JSON output with proper indentation −

import json# Sample dictionarydata = {"name": "Alice", "age": 25, "city": "London"}# Convert dictionary to JSON with indentationjson_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

Theseparators parameter controls the formatting of key-value pairs in JSON −

import json# Sample dictionarydata = {"name": "Alice", "age": 25, "city": "London"}# Convert dictionary to JSON with custom separatorsjson_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
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp