首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeError: UUID类型的对象不能被JSON序列化

TypeError: UUID类型的对象不能被JSON序列化
EN

Stack Overflow用户
提问于 2020-10-16 19:16:42
回答 3查看 8K关注 0票数 1

我正在构建一个相当大的JSON字典,其中我指定了几个uuids,如下所示:

代码语言:javascript
复制
import uuid

game['uuid'] = uuid.uuid1()

我得到了一个类型错误与以下回溯。我不知道问题是什么,因为我们可以在json对象中拥有UUID

代码语言:javascript
复制
Traceback (most recent call last):
  File "/Users/claycrosby/Desktop/coding/projects/gambling/scraper/sbtesting.py", line 182, in <module>
    game_json = json.dumps(game)
  File "/opt/miniconda3/envs/ds383/lib/python3.8/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/opt/miniconda3/envs/ds383/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/opt/miniconda3/envs/ds383/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/opt/miniconda3/envs/ds383/lib/python3.8/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type UUID is not JSON serializable
[Finished in 0.5s with exit code 1]
[cmd: ['/opt/miniconda3/envs/ds383/bin/python3', '/Users/claycrosby/Desktop/coding/projects/gambling/scraper/sbtesting.py']]
[dir: /Users/claycrosby/Desktop/coding/projects/gambling/scraper]
[path: /opt/miniconda3/bin:/opt/miniconda3/condabin:/Library/Frameworks/Python.framework/Versions/3.8/bin:/Library/Frameworks/Python.framework/Versions/3.8/bin:/Users/claycrosby/Desktop/coding/programs/pbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/go/bin]
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-10-16 19:33:44

uuid.UUID类本身不能序列化,但是对象可以用几种JSON兼容的格式表示。从help(uuid.UUID)中我们可以看到这些选项(尽管字节还需要更多的工作,因为它们也不是json )。

代码语言:javascript
复制
 |      bytes       the UUID as a 16-byte string (containing the six
 |                  integer fields in big-endian byte order)
 |  
 |      bytes_le    the UUID as a 16-byte string (with time_low, time_mid,
 |                  and time_hi_version in little-endian byte order)
 |  
 |      fields      a tuple of the six integer fields of the UUID,
 |                  which are also available as six individual attributes
 |                  and two derived attributes:
 |  
 |          time_low                the first 32 bits of the UUID
 |          time_mid                the next 16 bits of the UUID
 |          time_hi_version         the next 16 bits of the UUID
 |          clock_seq_hi_variant    the next 8 bits of the UUID
 |          clock_seq_low           the next 8 bits of the UUID
 |          node                    the last 48 bits of the UUID
 |  
 |          time                    the 60-bit timestamp
 |          clock_seq               the 14-bit sequence number
 |  
 |      hex         the UUID as a 32-character hexadecimal string
 |  
 |      int         the UUID as a 128-bit integer
 |  
 |      urn         the UUID as a URN as specified in RFC 4122

例如,如果您的API想要一个骨灰盒,您可以

代码语言:javascript
复制
>>> game = {'uuid': uuid.uuid1().urn}
>>> game
{'uuid': 'urn:uuid:56fabaca-0fe6-11eb-9910-c770eddca9e7'}
>>> json.dumps(game)
'{"uuid": "urn:uuid:56fabaca-0fe6-11eb-9910-c770eddca9e7"}'
票数 5
EN

Stack Overflow用户

发布于 2020-10-16 19:32:52

他的回答很好。但是,如果您最终不得不在太多地方按摩数据才能使其序列化,那么可以考虑编写您自己的JSON序列化类来完成它!例如,这里有一个将IPV4Addresses转换为字符串的方法:

代码语言:javascript
复制
from json import JSONEncoder, dumps

class TMCSerializer(JSONEncoder):

    def default(self, value: Any) -> str:
        """JSON serialization conversion function."""

        # If it's an IP, which is not normally
        # serializable, convert to string.
        if isinstance(value, IPv4Address):
            return str(value)

        # Here you can have other handling for your
        # UUIDs, or datetimes, or whatever else you
        # have.

        # Otherwise, default to super
        return super(TMCSerializer, self).default(value)

然后你就这样称呼它:

代码语言:javascript
复制
json_str = json.dumps(some_dict, cls=TMCSerializer)
票数 5
EN

Stack Overflow用户

发布于 2020-10-16 19:18:30

将其转换为字符串,而不是使用uuid.UUID对象:

代码语言:javascript
复制
game['uuid'] = str(uuid.uuid1())
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64395136

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档