Python到JSON的序列化在十进制上失败

编程入门 行业动态 更新时间:2024-10-27 22:20:38
本文介绍了Python到JSON的序列化在十进制上失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个包含一些小数的python对象.这导致json.dumps()损坏.

I have a python object which includes some decimals. This is causing the json.dumps() to break.

我从SO中获得了以下解决方案(例如 Python JSON序列化Decimal对象

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.

有什么建议可以做到这一点吗?

Any suggestions how to make this work?

谢谢.下面是我的代码.看起来dumps()甚至都没有进入专门的编码器.

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>

推荐答案

不(不再)建议您创建一个子类; json.dump()和json.dumps()函数采用default函数:

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)

演示:

>>> 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}'

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

The code you found only worked on Python 2.6 and overrides a private method that is no longer called in later versions.

更多推荐

Python到JSON的序列化在十进制上失败

本文发布于:2023-11-08 22:19:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1570602.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列化   Python   JSON   十进制上

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!