🔍 Code Extractor

class Neo4jEncoder

Maturity: 36

A custom JSON encoder that extends json.JSONEncoder to handle Neo4j-specific data types and Python objects that are not natively JSON serializable.

File:
/tf/active/vicechatdev/neo4j_schema_report.py
Lines:
10 - 22
Complexity:
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

  • json
  • neo4j
  • datetime

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function safe_json_serialize 53.7% similar

    Recursively converts Python objects into JSON-serializable formats, with special handling for datetime objects and objects with to_dict() methods.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function safe_json_dumps 52.8% similar

    Safely serializes Python objects to JSON format, handling NaN values and datetime objects that would otherwise cause serialization errors.

    From: /tf/active/vicechatdev/full_smartstat/services.py
  • function clean_for_json_v10 49.1% similar

    Recursively converts Python objects containing NumPy and Pandas data types into JSON-serializable native Python types.

    From: /tf/active/vicechatdev/vice_ai/smartstat_scripts/c385e1f5-fbf6-4832-8fd4-78ef8b72fc53/project_1/analysis.py
  • function clean_for_json_v3 49.0% similar

    Recursively converts Python objects (including NumPy and Pandas types) into JSON-serializable formats by handling special numeric types, NaN/Inf values, and nested data structures.

    From: /tf/active/vicechatdev/vice_ai/smartstat_scripts/f0a78968-1d2b-4fbe-a0c6-a372da2ce2a4/project_1/analysis.py
  • function _sanitize_properties 47.8% similar

    Sanitizes a dictionary of properties to ensure compatibility with Neo4j by converting complex objects to primitive types, extracting UIDs from DocUser objects, and preserving datetime objects.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
← Back to Browse