擅长:python、mysql、java
<p>那1买的答案很好。但是,如果最终不得不在太多地方对数据进行按摩以使其序列化,请考虑编写自己的JSON序列化类来为您做这件事!例如,这里有一个将IPV4地址转换为字符串的方法:</p>
<pre><code>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)
</code></pre>
<p>然后你这样称呼它:</p>
<pre><code>json_str = json.dumps(some_dict, cls=TMCSerializer)
</code></pre>