[英]How json dumps None to empty string
我希望 Python 的None
在 json 中编码为空字符串如何? 下面是json.dumps
的默认行为。
>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
我应该覆盖 json 编码器方法还是有其他方法?
输入数据并不像上面的例子那么简单,在每次请求时,它都可以更改为不同的数据结构。 很难写一个 function 来改变数据结构。
在您正在编码的 object 中,使用空字符串而不是None
。
这是一个未经测试的 function 遍历一系列嵌套字典以将所有None
值更改为''
。 添加对列表和元组的支持留给读者作为练习。:)
import copy
def scrub(x):
ret = copy.deepcopy(x)
# Handle dictionaries. Scrub all values
if isinstance(x, dict):
for k,v in ret.items():
ret[k] = scrub(v)
# Handle None
if x == None:
ret = ''
# Finished scrubbing
return ret
处理要编码的数据并用空字符串替换None
会更好。 毕竟,这就是你想要的。
这是一个稍微改进的版本,它也可以处理列表和元组:
def scrub(x):
# Converts None to empty string
ret = copy.deepcopy(x)
# Handle dictionaries, lits & tuples. Scrub all values
if isinstance(x, dict):
for k, v in ret.items():
ret[k] = scrub(v)
if isinstance(x, (list, tuple)):
for k, v in enumerate(ret):
ret[k] = scrub(v)
# Handle None
if x is None:
ret = ''
# Finished scrubbing
return ret
我在使用jsonschmea
模块时使用它。 似乎它无法处理None
类型,并抛出: jsonschema.exceptions.ValidationError: None is not of type u'string'
。 所以这可以解决问题。
您实际上可以使用json.JSONEncoder ,如果您有一个带有列表、元组、字典、字符串和 None 的 object,您可以使用 class 来替换之后显示的空字符串。
default
是原先用于将非 json 类型转换为 python 的方法,这次我们使用它来将 None 转换为空字符串。
encode
用于对 json 进行编码,这就是我们使用新默认值使用新方法的原因
class NoneToEmptyJSON(json.JSONEncoder):
def default(self, o):
if o == None:
o = ''
elif type(o) == dict:
return {self.default(key): self.default(value) for key, value in o.items()}
elif type(o) == list or type(o) == tuple:
return [self.default(item) for item in o]
return o
def encode(self, o):
return super().encode(self.default(o))
然后代替转储,您使用 class 编码
NoneToEmptyJSON().encode(['foo', {'bar': ('baz', None, 1.0, 2)}])
那么结果是:
'["foo", {"bar": ["baz", "", 1.0, 2]}]'
如果你想要缩进或其他东西,你也可以使用 params :
NoneToEmptyJSON(ensure_ascii=False, indent=2).encode(['foo', {'bar': ('baz', None, 1.0, 2)}])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.