or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-jsonfield

A reusable Django field that allows you to store validated JSON in your model.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/jsonfield@3.2.x

To install, run

npx @tessl/cli install tessl/pypi-jsonfield@3.2.0

index.mddocs/

jsonfield

A reusable Django model field that allows you to store validated JSON data in your model. jsonfield provides JSONField and JSONCharField classes that handle JSON serialization, deserialization, validation, and basic Django ORM integration for JSON data.

Note: This package is deprecated as Django 3.1+ includes native JSONField support. Use Django's built-in models.JSONField for new projects.

Package Information

  • Package Name: jsonfield
  • Language: Python
  • Installation: pip install jsonfield
  • Dependencies: Django >= 4.2, Python >= 3.10

Core Imports

from jsonfield import JSONField, JSONCharField

Individual imports:

from jsonfield import JSONField
from jsonfield import JSONCharField

Alternative submodule imports:

from jsonfield import fields
from jsonfield.fields import JSONField, JSONCharField
from jsonfield.json import JSONString, checked_loads
from jsonfield.encoder import JSONEncoder

Basic Usage

from django.db import models
from jsonfield import JSONField, JSONCharField

class MyModel(models.Model):
    # Basic JSON field (unlimited length)
    data = JSONField()
    
    # JSON field with default value
    settings = JSONField(default={'theme': 'light', 'lang': 'en'})
    
    # JSON field with length constraint
    small_data = JSONCharField(max_length=255)
    
    # Nullable JSON field
    optional_data = JSONField(null=True, blank=True)

# Usage in views/code
obj = MyModel.objects.create(
    data={'user_id': 123, 'preferences': ['dark_mode', 'notifications']},
    settings={'theme': 'dark'},
    small_data={'status': 'active'},
    optional_data=None
)

# Access the data
print(obj.data['user_id'])  # 123
print(obj.settings['theme'])  # 'dark'

Capabilities

JSONField

Primary Django model field for storing JSON data without length constraints. Built on TextField with JSON serialization/deserialization.

class JSONField(models.TextField):
    """
    JSONField is a generic textfield that serializes/deserializes JSON objects.
    
    Parameters:
    - dump_kwargs (dict, optional): JSON serialization options passed to json.dumps()
    - load_kwargs (dict, optional): JSON deserialization options passed to json.loads()
    - All standard Django field parameters (null, blank, default, etc.)
    """
    
    def __init__(self, *args, dump_kwargs=None, load_kwargs=None, **kwargs): ...
    def to_python(self, value): ...
    def from_db_value(self, value, expression, connection): ...
    def get_prep_value(self, value): ...
    def value_to_string(self, obj): ...
    def formfield(self, **kwargs): ...
    def get_default(self): ...
    
    # JSONField-specific formfield enhancement
    def formfield(self, **kwargs):
        """
        Returns form field with enhanced defaults for TextArea widget.
        Automatically sets 'indent': 4 and 'ensure_ascii': False for better formatting.
        """

Usage Examples

from collections import OrderedDict
from jsonfield import JSONField

class ConfigModel(models.Model):
    # Basic usage
    config = JSONField()
    
    # With default value
    settings = JSONField(default={'enabled': True})
    
    # With custom JSON serialization (pretty printing)
    pretty_config = JSONField(
        dump_kwargs={'indent': 4, 'ensure_ascii': False}
    )
    
    # Preserve key order with OrderedDict
    ordered_config = JSONField(
        load_kwargs={'object_pairs_hook': OrderedDict}
    )
    
    # Custom encoder for special data types
    complex_data = JSONField(
        dump_kwargs={'cls': MyCustomEncoder},
        load_kwargs={'object_hook': my_decoder_function}
    )

JSONCharField

Character-based Django model field for storing JSON data with length constraints. Built on CharField with JSON serialization/deserialization.

class JSONCharField(models.CharField):
    """
    JSONCharField is a generic CharField that serializes/deserializes JSON objects.
    
    Parameters:
    - max_length (int): Maximum length of the JSON string representation
    - dump_kwargs (dict, optional): JSON serialization options passed to json.dumps()
    - load_kwargs (dict, optional): JSON deserialization options passed to json.loads()
    - All standard Django CharField parameters
    """
    
    def __init__(self, max_length, *args, dump_kwargs=None, load_kwargs=None, **kwargs): ...

Usage Examples

class CompactModel(models.Model):
    # Small JSON data with length constraint
    status = JSONCharField(max_length=100, default={'active': True})
    
    # Short configuration strings
    settings = JSONCharField(max_length=255)

Form Field Integration

Django form field for JSON input validation and handling in web forms.

class JSONField(forms.CharField):
    """
    Form field for JSON input validation.
    
    Parameters:
    - dump_kwargs (dict, optional): JSON serialization options
    - load_kwargs (dict, optional): JSON deserialization options
    - All standard Django CharField parameters
    """
    
    def to_python(self, value): ...
    def bound_data(self, data, initial): ...
    def prepare_value(self, value): ...

JSON Utilities

Helper functions and classes for JSON processing.

def checked_loads(value, **kwargs):
    """
    Safe JSON loading that prevents double-loading.
    
    Parameters:
    - value: Value to load (str, list, dict, int, float, JSONString, or None)
    - **kwargs: Additional arguments for json.loads
    
    Returns:
    - Parsed Python object or original value if already loaded
    """

class JSONString(str):
    """
    Marker class to differentiate loaded from unloaded JSON strings.
    Inherits from str but indicates the string has been JSON-loaded.
    """

class JSONEncoder(json.JSONEncoder):
    """
    Extended JSON encoder supporting Django model types.
    
    Supports:
    - datetime.datetime, datetime.date, datetime.time, datetime.timedelta
    - decimal.Decimal, uuid.UUID
    - Django QuerySet, Promise objects
    - bytes, numpy arrays (if available)
    - Iterables and mappings
    """
    
    def default(self, obj): ...

# Constants
DEFAULT_DUMP_KWARGS = {'cls': JSONEncoder}
DEFAULT_LOAD_KWARGS = {}

Configuration Options

Null Value Handling

Controls how null values are stored and queried:

class MyModel(models.Model):
    # null=True: nulls stored as database NULL, supports isnull lookup
    nullable_json = JSONField(null=True, blank=True)
    
    # null=False: nulls stored as JSON "null" string
    non_nullable_json = JSONField(null=False)

# Querying
MyModel.objects.filter(nullable_json=None)  # Works for both
MyModel.objects.filter(nullable_json__isnull=True)  # Only works with null=True

Custom JSON Processing

import json
from collections import OrderedDict

class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, complex):
            return {'__complex__': True, 'real': obj.real, 'imag': obj.imag}
        return super().default(obj)

def complex_decoder(dct):
    if '__complex__' in dct:
        return complex(dct['real'], dct['imag'])
    return dct

class MyModel(models.Model):
    # Custom encoder/decoder
    complex_data = JSONField(
        dump_kwargs={'cls': CustomEncoder},
        load_kwargs={'object_hook': complex_decoder}
    )
    
    # Preserve key ordering
    ordered_data = JSONField(
        load_kwargs={'object_pairs_hook': OrderedDict}
    )
    
    # Pretty printing for readability
    readable_data = JSONField(
        dump_kwargs={'indent': 4, 'ensure_ascii': False}
    )

Types

class JSONFieldMixin(models.Field):
    """
    Base mixin providing core JSON field functionality.
    
    Attributes:
    - form_class: Associated form field class
    - dump_kwargs: JSON serialization options
    - load_kwargs: JSON deserialization options
    """
    
    form_class = forms.JSONField
    
    def __init__(self, *args, dump_kwargs=None, load_kwargs=None, **kwargs): ...
    def deconstruct(self): ...
    def to_python(self, value): ...
    def from_db_value(self, value, expression, connection): ...
    def get_prep_value(self, value): ...
    def value_to_string(self, obj): ...
    def formfield(self, **kwargs): ...
    def get_default(self): ...

class InvalidJSONInput(str):
    """
    Marker class for invalid JSON input in forms.
    Used internally to handle form validation errors.
    """

Error Handling

The package handles several error conditions:

  • ValidationError: Raised for invalid JSON in model fields during validation
  • json.JSONDecodeError: Handled internally with runtime warnings for corrupted database data
  • ValueError: Converted to ValidationError for timezone-aware datetime objects
from django.forms import ValidationError

# Invalid JSON will raise ValidationError
try:
    field.to_python('{"invalid": json}')
except ValidationError as e:
    print(e.message)  # "Enter valid JSON."

Migration from Django's JSONField

For projects migrating to Django's native JSONField:

  1. Replace imports: from django.db import modelsmodels.JSONField
  2. Update field definitions: JSONField()models.JSONField()
  3. Run migrations: python manage.py makemigrations && python manage.py migrate
  4. For complex migrations, use data migrations to preserve field behavior differences