🔍 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, Python datetime, 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. Raises TypeError if the object cannot be serialized.

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 use this encoder when serializing Neo4j query results to JSON to avoid serialization errors with Neo4j-specific types
  • Pass the class (not an instance) to json.dumps() or json.dump() using the cls parameter: json.dumps(data, cls=Neo4jEncoder)
  • The encoder handles sets by converting them to lists, which means the order may not be preserved and duplicates will be removed
  • ISO format datetime strings are returned, which are widely compatible but may need parsing on the receiving end
  • This encoder only handles the specific types defined in the default() method; other custom types will still raise TypeError
  • The encoder is stateless and thread-safe, so a single class reference can be reused across multiple serialization operations
  • Consider extending this class if you need to handle additional Neo4j types like Point, Duration, or custom node/relationship objects

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function generate_python_snippets 43.6% similar

    Generates a Python file containing code snippets and helper functions for interacting with a Neo4j graph database based on the provided schema information.

    From: /tf/active/vicechatdev/neo4j_schema_report.py
  • function generate_diagram_data 41.2% similar

    Transforms Neo4j schema information into a structured format suitable for graph visualization, creating separate node and edge data structures.

    From: /tf/active/vicechatdev/neo4j_schema_report.py
  • function generate_neo4j_schema_report 40.8% similar

    Generates a comprehensive schema report of a Neo4j graph database, including node labels, relationships, properties, constraints, indexes, and sample data, outputting multiple report formats (JSON, HTML, Python snippets, Cypher examples).

    From: /tf/active/vicechatdev/neo4j_schema_report.py
  • class V4JsonFormat 40.5% similar

    V4JsonFormat is a class that implements OData V4 JSON format specifications, managing metadata levels, IEEE754 compatibility, and streaming options for JSON serialization.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/odata/v4/json_format.py
  • class DateTimeTimeZone 38.1% similar

    A class representing a date, time, and time zone combination for a specific point in time, compatible with Office 365 API structures.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/outlook/calendar/dateTimeTimeZone.py
← Back to Browse