UUID('…') is not JSON serializable

前端 未结 4 1337
生来不讨喜
生来不讨喜 2020-12-05 23:19

I get this error when i try to pass the UUID attribute to url parameter.

urlpatterns = [
    url(r\'^historia-clinica/(?P[W\\d\\-]+)/$\', ClinicH         


        
相关标签:
4条回答
  • 2020-12-05 23:44

    I use convert function for this, it is simple and clean.

    import json
    from uuid import UUID
    def uuid_convert(o):
            if isinstance(o, UUID):
                return o.hex
    
    json.dumps(users,indent=4,default=uuid_convert)
    
    0 讨论(0)
  • 2020-12-05 23:52

    There is a bug ticket on Django regarding this issue however a custom so called 'complex encoder' by python docs can help you.

    import json
    from uuid import UUID
    
    
    class UUIDEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, UUID):
                # if the obj is uuid, we simply return the value of uuid
                return obj.hex
            return json.JSONEncoder.default(self, obj)
    

    Now if we did something like this

    json.dumps(my_object, cls=UUIDEncoder)
    

    Your uuid field should be encoded.

    0 讨论(0)
  • 2020-12-05 23:59

    I had this same problem with a UUID field in a database model that I wanted to print out for debugging. I found that the pprint() function from the pprint module can handle this. You can also give it an indent argument to get the same kind of indented output that you would get from json.dumps()

    https://docs.python.org/3/library/pprint.html#pprint.pprint

    Example:

    >>> import uuid
    >>> import pprint
    >>> import json
    >>> x = uuid.UUID('12345678123456781234567812345678')
    >>> x
    UUID('12345678-1234-5678-1234-567812345678')
    >>> print(x)
    12345678-1234-5678-1234-567812345678
    >>> json.dumps(x)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ...
    ...
        raise TypeError(repr(o) + " is not JSON serializable")
    TypeError: UUID('12345678-1234-5678-1234-567812345678') is not JSON serializable
    >>> pprint.pprint(x)
    UUID('12345678-1234-5678-1234-567812345678')
    
    0 讨论(0)
  • 2020-12-06 00:06

    For using the UUID in a URL like that, you should pass it as a string:

     return redirect(reverse('namespace:name', kwargs={'uuid' : str(object.id)}))
    

    FYI - it looks like WIMs answer is a bit more thorough. Your regex should certainly be tightened up. If you end up using the string representation of the slug, you'll want a regex like this: [A-Za-z0-9\-]+ which allows for alphanumerics and hyphens.

    0 讨论(0)
提交回复
热议问题