TypeError: In order to allow non-dict objects to be serialized set the safe

created at 07-17-2021 views: 2

Using JsonResponse to return data encountered an error in development:

TypeError: In order to allow non-dict objects to be serialized set the safe

views.py

def userProfile(request):
    posts = User.objects.order_by('id')[:10].reverse()
    return JsonResponse(posts)

JsonResponse source code:

class JsonResponse(HttpResponse):
    """
    An HTTP response class that consumes data to be serialized to JSON.

    :param data: Data to be dumped into json. By default only ``dict`` objects
      are allowed to be passed due to a security flaw before EcmaScript 5. See
      the ``safe`` parameter for more information.
    :param encoder: Should be a json encoder class. Defaults to
      ``django.core.serializers.json.DjangoJSONEncoder``.
    :param safe: Controls if only ``dict`` objects may be serialized. Defaults
      to ``True``.
    :param json_dumps_params: A dictionary of kwargs passed to json.dumps().
    """

    def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                 json_dumps_params=None, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError(
                'In order to allow non-dict objects to be serialized set the '
                'safe parameter to False.'
            )
        if json_dumps_params is None:
            json_dumps_params = {}
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder, **json_dumps_params)
        super().__init__(content=data, **kwargs)

According to the source code, it is because the data parameter passed in is not a dictionary.

Solution

def userProfile(request):
    posts = User.objects.order_by('id')[:10].reverse()
    return JsonResponse(posts, safe=False)
Please log in to leave a comment.