class Neo4jEncoder
A custom JSON encoder that extends json.JSONEncoder to handle Neo4j-specific data types and Python objects that are not natively JSON serializable.
/tf/active/vicechatdev/neo4j_schema_report.py
10 - 22
simple
Purpose
This encoder class provides serialization support for Neo4j DateTime objects, Python datetime objects, and Python sets when converting data to JSON format. It's particularly useful when working with Neo4j graph database query results that need to be serialized to JSON, as Neo4j returns custom data types that the standard JSON encoder cannot handle. The class overrides the default() method to provide custom serialization logic for these specific types while delegating all other types to the parent JSONEncoder class.
Source Code
class Neo4jEncoder(json.JSONEncoder):
def default(self, obj):
# Handle Neo4j DateTime objects
if isinstance(obj, time.DateTime):
return obj.to_native().isoformat()
# Handle Python datetime objects
elif isinstance(obj, datetime):
return obj.isoformat()
# Handle sets by converting to lists
elif isinstance(obj, set):
return list(obj)
# Let the base class handle anything else
return super(Neo4jEncoder, self).default(obj)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
json.JSONEncoder | - |
Parameter Details
obj: The Python object to be serialized. This parameter is passed automatically by the JSON encoding process when an object cannot be serialized by the default encoder. It can be a Neo4j DateTime object, Python datetime object, set, or any other Python object.
Return Value
The default() method returns a JSON-serializable representation of the input object. For Neo4j DateTime objects, it returns an ISO format string. For Python datetime objects, it returns an ISO format string. For sets, it returns a list. For all other types, it delegates to the parent class's default() method, which either serializes the object or raises a TypeError if the object is not serializable.
Class Interface
Methods
default(self, obj) -> Any
Purpose: Converts non-JSON-serializable objects to JSON-serializable formats. This method is called by the JSON encoder when it encounters an object it cannot serialize.
Parameters:
obj: The object to be serialized. Can be a Neo4j DateTime object, Python datetime object, set, or any other Python object
Returns: A JSON-serializable representation of the object: ISO format string for datetime objects, list for sets, or delegates to parent class for other types
Dependencies
jsonneo4jdatetime
Required Imports
import json
from neo4j import time
from datetime import datetime
Usage Example
import json
from neo4j import time
from datetime import datetime
# Assuming Neo4jEncoder class is defined
# Example 1: Encoding a dictionary with datetime
data = {
'name': 'John',
'created_at': datetime(2024, 1, 15, 10, 30, 0),
'tags': {'python', 'neo4j', 'json'}
}
json_string = json.dumps(data, cls=Neo4jEncoder)
print(json_string)
# Output: {"name": "John", "created_at": "2024-01-15T10:30:00", "tags": ["python", "neo4j", "json"]}
# Example 2: Encoding Neo4j query results
# Assuming you have Neo4j DateTime objects from a query
neo4j_data = {
'event': 'login',
'timestamp': time.DateTime(2024, 1, 15, 10, 30, 0),
'user_roles': {'admin', 'user'}
}
json_output = json.dumps(neo4j_data, cls=Neo4jEncoder)
print(json_output)
# Example 3: Using with json.dump() to write to file
with open('output.json', 'w') as f:
json.dump(data, f, cls=Neo4jEncoder, indent=2)
Best Practices
- Always pass Neo4jEncoder as the 'cls' parameter to json.dumps() or json.dump() when serializing data that may contain Neo4j types, datetime objects, or sets
- The encoder handles only specific types (Neo4j DateTime, Python datetime, and sets). For other custom types, you may need to extend this class further
- The encoder converts sets to lists, which means the order may not be preserved and the uniqueness constraint is lost after deserialization
- When deserializing JSON back to Python objects, remember that datetime strings will remain as strings unless you implement custom deserialization logic
- This encoder is stateless and thread-safe, so a single instance can be reused across multiple encoding operations
- The class does not need to be instantiated manually; pass it as a class reference to json.dumps() or json.dump()
- If you need to handle additional Neo4j types (like Point, Duration, etc.), extend the default() method with additional isinstance checks
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function safe_json_serialize 53.7% similar
-
function safe_json_dumps 52.8% similar
-
function clean_for_json_v10 49.1% similar
-
function clean_for_json_v3 49.0% similar
-
function _sanitize_properties 47.8% similar