我有一个python对象,其中包含一些小数.这导致了json.垃圾桶要打碎了.

I got the following solution from SO (e.g. Python JSON serialize a Decimal object) but the recoomended solution still does not work. Python website - has the exact same answer.

有什么建议可以让这一切顺利进行吗?

Thanks. Below is my code. It looks like the dumps() doesn't even go into the specialized encoder.

clayton@mserver:~/python> cat test1.py
import json, decimal

class DecimalEncoder(json.JSONEncoder):
        def _iterencode(self, o, markers=None):
                print "here we go o is a == ", type(o)
                if isinstance(o, decimal.Decimal):
                        print "woohoo! got a decimal"
                        return (str(o) for o in [o])
                return super(DecimalEncoder, self)._iterencode(o, markers)

z = json.dumps( {'x': decimal.Decimal('5.5')}, cls=DecimalEncoder )
print z
clayton@mserver:~/python> python test1.py
Traceback (most recent call last):
  File "test1.py", line 11, in <module>
    z = json.dumps( {'x': decimal.Decimal('5.5')}, cls=DecimalEncoder )
  File "/home/clayton/python/Python-2.7.3/lib/python2.7/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/home/clayton/python/Python-2.7.3/lib/python2.7/json/encoder.py", line 201, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/home/clayton/python/Python-2.7.3/lib/python2.7/json/encoder.py", line 264, in iterencode
    return _iterencode(o, 0)
  File "/home/clayton/python/Python-2.7.3/lib/python2.7/json/encoder.py", line 178, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: Decimal('5.5') is not JSON serializable
clayton@mserver:~/python>

推荐答案

It is not (no longer) recommended you create a subclass; the json.dump() and json.dumps() functions take a default function:

def decimal_default(obj):
    if isinstance(obj, decimal.Decimal):
        return float(obj)
    raise TypeError

json.dumps({'x': decimal.Decimal('5.5')}, default=decimal_default)

Demo:

>>> def decimal_default(obj):
...     if isinstance(obj, decimal.Decimal):
...         return float(obj)
...     raise TypeError
... 
>>> json.dumps({'x': decimal.Decimal('5.5')}, default=decimal_default)
'{"x": 5.5}'

您发现的代码只适用于Python2.6,并且覆盖了在以后的版本中不再调用的私有方法.

Json相关问答推荐

我如何知道TJSONNumber是double还是double?

在Jenkins中使用ReadJSON读取json子元素

Vega图表计数聚合如果数据值为空数组则不显示任何内容,如何解决此问题?

时间序列的Vega Lite分组条形图

修改Deneb图表中工具提示的字体大小

在AWS步骤函数中将字符串解析为JSON&S映射状态

如何在我的响应模型中修复此问题:[期望的值类型为';Map<;Dynamic,Dynamic&>;,但获得的值类型为';NULL&39;]

组合不同属性的Jolt Spec

规范化JSON数据

在 VS Code 中将一个正则表达式替换为另一个正则表达式

将 std::可选值存储到 json 文件 C++

从包含 JSON 对象序列的文件中获取第一个 JSON 对象

使用 JQ 获取 JSON 中的替代元素(输出:JSON 对象)

使用 @ResponseBody 自定义 HttpMessageConverter 来做 Json 事情

Json.Net:用于自定义命名的 JsonSerializer-Attribute

如何在 Perl 中将简单的哈希转换为 json?

JSON 使用 simplejson 序列化 Django 模型

从 VS 2017 Azure Function 开发中的 local.settings.json 读取值

将循环 struct 转换为 JSON - 有什么方法可以找到它抱怨的字段?

使用适用于 Python 的 Google API - 我从哪里获取 client_secrets.json 文件?