<p><code>uuid.UUID</code>类本身不能被JSON序列化,但对象可以用几种JSON兼容的格式表示。从<code>help(uuid.UUID)</code>我们可以看到这些选项(尽管字节也不是json,所以需要做更多的工作)</p>
<pre><code> | 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
</code></pre>
<p>例如,如果您的API需要URN,您应该</p>
<pre><code>>>> 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"}'
</code></pre>