HTTP responses

class django_orjson.http.JsonResponse(data, default=<function default>, option=None, **kwargs)[source]

An HTTP response class that consumes data to be serialized to JSON.

Parameters:
  • data (Any) – Data to be dumped into json.

  • default (Callable[[Any], Any]) – A callable that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

  • option (int | None) –

    A bitfield of orjson options.

    A subclass of Django’s HttpResponse that serializes its content with orjson.dumps() instead of the standard library’s json.dumps(). This provides faster serialization and native support for additional types such as datetime, UUID, and dataclasses.

    Usage mirrors Django’s built-in JsonResponse:

    from django_orjson.http import JsonResponse
    
    
    def my_view(request):
        return JsonResponse({"key": "value"})
    

  • kwargs (Any)

Unlike Django’s class, there is no safe parameter: any serializable object may be passed as data, including non-dict objects like lists. Django deprecated safe in version 6.2 (Ticket #36905), as it guarded against a JSON hijacking vulnerability that only existed in long-obsolete browsers.

param data:

The object to serialize.

param default:

Passes through to orjson’s default parameter. Defaults to django_orjson.default(), for extended type support.

Pass a different callable to handle additional types, or chain to django_orjson.default() for the built-in behaviour:

import pathlib

from django_orjson import default as base_default


def default(obj):
    if isinstance(obj, pathlib.Path):
        return str(obj)
    return base_default(obj)


JsonResponse({"path": pathlib.Path("/tmp/file.txt")}, default=default)
param option:

An optional integer of orjson option flags. See the orjson documentation for available options. Multiple options can be combined with |:

import orjson

JsonResponse({"b": 1, "a": 2}, option=orjson.OPT_SORT_KEYS)
param kwargs:

Other HttpResponse parameters.