UUID('…') is not JSON serializable

前端 未结 4 1362
生来不讨喜
生来不讨喜 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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 "", line 1, in 
    ...
    ...
        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')
    

提交回复
热议问题