question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Object of type 'Hashid' is not JSON serializable

See original GitHub issue

The regular JSON encoders can’t handle the Hashid object, so we had to override the encoder to use the hashed value instead of the instance:

class HashidJSONEncoder(DjangoJSONEncoder):
    def default(self, o):
        if isinstance(o, Hashid):
            return str(o)
        return super().default(o)

This is not that surprising or new, but I’d leave a note.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:1
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
tom-and-jarycommented, Aug 15, 2020

Make sure that each models.ForeignKey is declared in Serializer:

like this:

user = serializers.PrimaryKeyRelatedField(
        pk_field=HashidSerializerCharField(source_field='appname.modelname.id'),
        read_only=True)

chinese version: 在model里,所有用了models.ForeignKey的字段, 在Serializer文件里,必须 用这种格式:

user = serializers.PrimaryKeyRelatedField(
        pk_field=HashidSerializerCharField(source_field='appname.modelname.id'),
        read_only=True)

不然就会提示错误, 而且很难排查 , 我花了一整天都没有找出原因,最后通过删减字段,才搞定

0reactions
sdementencommented, Dec 9, 2020

I have the issue when the package django-impersonate push the hashid of my customer user class in the session and django tries to sign the session. For this, django convert the content of the session to JSON which triggers the exception.

Traceback (most recent call last):
  File "...\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "...\lib\site-packages\django\utils\deprecation.py", line 116, in __call__
    response = self.process_response(request, response)
  File "...\lib\site-packages\django\contrib\sessions\middleware.py", line 63, in process_response
    request.session.save()
  File "...\lib\site-packages\django\contrib\sessions\backends\db.py", line 83, in save
    obj = self.create_model_instance(data)
  File "...\lib\site-packages\django\contrib\sessions\backends\db.py", line 70, in create_model_instance
    session_data=self.encode(data),
  File "...\lib\site-packages\django\contrib\sessions\backends\base.py", line 114, in encode
    return signing.dumps(
  File "...\lib\site-packages\django\core\signing.py", line 110, in dumps
    data = serializer().dumps(obj)
  File "...\lib\site-packages\django\core\signing.py", line 87, in dumps
    return json.dumps(obj, separators=(',', ':')).encode('latin-1')
  File "...\Lib\json\__init__.py", line 234, in dumps
    return cls(
  File "...\Lib\json\encoder.py", line 206, in encode
    chunks = list(chunks)
  File "...\Lib\json\encoder.py", line 442, in _iterencode
    yield from _iterencode_dict(o, _current_indent_level)
  File "...\Lib\json\encoder.py", line 413, in _iterencode_dict
    yield from chunks
  File "...\Lib\json\encoder.py", line 449, in _iterencode
    o = _default(o)
  File "...\Lib\json\encoder.py", line 182, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Hashid is not JSON serializable

The content of the session data (in session_data=self.encode(data), in the traceback) that will be JSON serialized is {..., '_impersonate': Hashid(2): b3ZRvZr, '_impersonate_start': 1607524600.914942, ...}.

Read more comments on GitHub >

github_iconTop Results From Across the Web

TypeError: Object of type date is not JSON serializable
The query_dict contains date objects which are not JSON serializable and by default Django will serialize session data using JSON.
Read more >
django-hashid-field - PyPI
Allows lookups and filtering by hashid string or Hashid object and ... don't you will get an error such as “Hashid(60): N8VNa8z is...
Read more >
Django object is not JSON serializable | Edureka Community
I have the following code for serializing the queryset; def render_to_response(self, context, ** ... both django objects and dicts.
Read more >
[Solved] DJANGO: object of type map is not JSON serializable
The map() function[^] returns an iterator and you must convert it to a list before you can serialize it. Python.
Read more >
HashIds Support - djangorestframework-serializer-extensions
Enabling HashIds. Serializer extensions also provides support for HashIds. Publicly exposing database IDs to your end users is often not a good idea, ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found