我在用json编码无穷大时遇到了麻烦。
json.dumps会将其转换为"Infinity",但我希望它将其转换为null或其他我选择的值。
不幸的是,只有当转储还不能理解对象时,设置default参数才能起作用,否则默认处理程序就会被绕过。
有没有办法对对象进行预编码,更改类型/类的默认编码方式,或者在正常编码之前将某个类型/类转换为不同的对象?
发布于 2013-07-07 00:11:44
请看这里的源代码:http://hg.python.org/cpython/file/7ec9255d4189/Lib/json/encoder.py
如果你继承了JSONEncoder的子类,你可以只覆盖iterencode(self, o, _one_shot=False)方法,它有显式的用于无限的特殊大小写(在内部函数中)。
为了使其可重用,您还需要修改__init__以获取一些新的选项,并将它们存储在类中。
或者,您可以从pypi中选择一个json库,它具有您正在寻找的适当的可扩展性:https://pypi.python.org/pypi?%3Aaction=search&term=json&submit=search
下面是一个例子:
import json
class FloatEncoder(json.JSONEncoder):
def __init__(self, nan_str = "null", **kwargs):
super(FloatEncoder,self).__init__(**kwargs)
self.nan_str = nan_str
# uses code from official python json.encoder module.
# Same licence applies.
def iterencode(self, o, _one_shot=False):
"""Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
"""
if self.check_circular:
markers = {}
else:
markers = None
if self.ensure_ascii:
_encoder = json.encoder.encode_basestring_ascii
else:
_encoder = json.encoder.encode_basestring
if self.encoding != 'utf-8':
def _encoder(o, _orig_encoder=_encoder,
_encoding=self.encoding):
if isinstance(o, str):
o = o.decode(_encoding)
return _orig_encoder(o)
def floatstr(o, allow_nan=self.allow_nan,
_repr=json.encoder.FLOAT_REPR,
_inf=json.encoder.INFINITY,
_neginf=-json.encoder.INFINITY,
nan_str = self.nan_str):
# Check for specials. Note that this type of test is
# processor and/or platform-specific, so do tests which
# don't depend on the internals.
if o != o:
text = nan_str
elif o == _inf:
text = 'Infinity'
elif o == _neginf:
text = '-Infinity'
else:
return _repr(o)
if not allow_nan:
raise ValueError(
"Out of range float values are not JSON compliant: " +
repr(o))
return text
_iterencode = json.encoder._make_iterencode(
markers, self.default, _encoder, self.indent, floatstr,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, _one_shot)
return _iterencode(o, 0)
example_obj = {
'name': 'example',
'body': [
1.1,
{"3.3": 5, "1.1": float('Nan')},
[float('inf'), 2.2]
]}
print json.dumps(example_obj, cls=FloatEncoder)发布于 2013-07-06 23:10:32
不,没有简单的方法来实现这一点。事实上,根据标准,NaN和Infinity浮点值根本不应该用json序列化。Python使用标准的扩展。您可以通过向dumps传递allow_nan=False参数来使python编码符合标准,但是即使您提供了一个default函数,这也会引发一个用于无限/ can的ValueError。
你有两种方法来做你想做的事情:
JSONEncoder并更改这些值的编码方式。请注意,您必须考虑序列可能包含无穷大值等情况。AFAIK没有API可用于重新定义特定类的对象的编码方式。None或您想要编码的其他对象。一种不太健壮但简单得多的解决方案是修改编码数据,例如用null替换所有Infinity子字符串
>>> import re
>>> infty_regex = re.compile(r'\bInfinity\b')
>>> def replace_infinities(encoded):
... regex = re.compile(r'\bInfinity\b')
... return regex.sub('null', encoded)
...
>>> import json
>>> replace_infinities(json.dumps([1, 2, 3, float('inf'), 4]))
'[1, 2, 3, null, 4]'显然,您应该考虑字符串中的文本Infinity等,所以即使在这里,一个健壮的解决方案也不是直接的,也不是优雅的。
发布于 2013-07-06 23:47:26
你可以按照下面的思路做一些事情:
import json
import math
target=[1.1,1,2.2,float('inf'),float('nan'),'a string',int(2)]
def ffloat(f):
if not isinstance(f,float):
return f
if math.isnan(f):
return 'custom NaN'
if math.isinf(f):
return 'custom inf'
return f
print 'regular json:',json.dumps(target)
print 'customized:',json.dumps(map(ffloat,target)) 打印:
regular json: [1.1, 1, 2.2, Infinity, NaN, "a string", 2]
customized: [1.1, 1, 2.2, "custom inf", "custom NaN", "a string", 2]如果你想处理嵌套的数据结构,这也不是很难:
import json
import math
from collections import Mapping, Sequence
def nested_json(o):
if isinstance(o, float):
if math.isnan(o):
return 'custom NaN'
if math.isinf(o):
return 'custom inf'
return o
elif isinstance(o, basestring):
return o
elif isinstance(o, Sequence):
return [nested_json(item) for item in o]
elif isinstance(o, Mapping):
return dict((key, nested_json(value)) for key, value in o.iteritems())
else:
return o
nested_tgt=[1.1,{1.1:float('inf'),3.3:5},(float('inf'),2.2),]
print 'regular json:',json.dumps(nested_tgt)
print 'nested json',json.dumps(nested_json(nested_tgt))打印:
regular json: [1.1, {"3.3": 5, "1.1": Infinity}, [Infinity, 2.2]]
nested json [1.1, {"3.3": 5, "1.1": "custom inf"}, ["custom inf", 2.2]]https://stackoverflow.com/questions/17503981
复制相似问题