json - 使用 python 3 专门化 JSON 对象编码

标签 json python-3.x

由于Python3中dict.values()和keys()的更改,我遇到了一些麻烦。

我的旧代码是这样的:

import json
class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, complex):
            return [obj.real, obj.imag]
        return json.JSONEncoder.default(self, obj)

a = { '1' : 2 + 1j, '2' : 4 + 2j }

print(json.dumps(a.values(), cls=ComplexEncoder))

这在 Python 3.3+ 上会引发异常:

TypeError: dict_values([(2+1j), (4+2j)]) is not JSON serializable

简单的解决方法是执行 list(a.values()),对我来说问题是我在代码中有很多类似的实例。有没有办法扩展 ComplexEncoder 以便迭代 查看?

最佳答案

您可以将可迭代编码为列表:

class IterEncoder(json.JSONEncoder):
    def default(self, obj):
        try:
            return list(obj)
        except TypeError:
            return super().default(obj)

class ComplexEncoder(IterEncoder):
    def default(self, obj):
        if isinstance(obj, complex):
            return [obj.real, obj.imag]

        return super().default(obj)

关于json - 使用 python 3 专门化 JSON 对象编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20975247/

相关文章:

javascript - 为什么 JSON 文件中的列表项返回未定义的 jQuery?

c# - 将 javascript 与 asp.net 连接起来

python - 带 pandas 的水平条形图左侧的输出表

python-3.x - 如何从 Python 中的文本文件打印名称

python - Pickle 和装饰类(PicklingError : not the same object)

python - 查找列表的最大值(Python)

java - REST:客户端可以通过 POST 传递包装对象吗?

android - 从 JSON 数组创建标记 php mySQL Google Maps v2 android

json - BitTorrent KRPC 使用 BEncode 而不是 BSON 背后的原因是什么?

python - 模块未找到错误 : No module named 'pip.commands'