A reusable Django field that allows you to store validated JSON in your model.
npx @tessl/cli install tessl/pypi-jsonfield@3.2.0A 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.
pip install jsonfieldfrom jsonfield import JSONField, JSONCharFieldIndividual imports:
from jsonfield import JSONField
from jsonfield import JSONCharFieldAlternative submodule imports:
from jsonfield import fields
from jsonfield.fields import JSONField, JSONCharField
from jsonfield.json import JSONString, checked_loads
from jsonfield.encoder import JSONEncoderfrom 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'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.
"""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}
)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): ...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)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): ...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 = {}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=Trueimport 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}
)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.
"""The package handles several error conditions:
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."For projects migrating to Django's native JSONField:
from django.db import models → models.JSONFieldJSONField() → models.JSONField()python manage.py makemigrations && python manage.py migrate