[英]How json dumps None to empty string
I want Python's None
to be encoded in json as empty string how?我希望 Python 的
None
在 json 中编码为空字符串如何? Below is the default behavior of json.dumps
.下面是
json.dumps
的默认行为。
>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
Should I overwrite the json encoder method or is there any other way?我应该覆盖 json 编码器方法还是有其他方法?
Input data is not that simple as in above example, on every request it could be changed to different data structure.输入数据并不像上面的例子那么简单,在每次请求时,它都可以更改为不同的数据结构。 Its difficult to write a function for changing data structure.
很难写一个 function 来改变数据结构。
In the object you're encoding, use an empty string instead of a None
.在您正在编码的 object 中,使用空字符串而不是
None
。
Here's an untested function that walks through a series of nested dictionaries to change all None
values to ''
.这是一个未经测试的 function 遍历一系列嵌套字典以将所有
None
值更改为''
。 Adding support for lists and tuples is left as an exercise to the reader.:)添加对列表和元组的支持留给读者作为练习。:)
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
It would be better to process the data you want to encode and replace None
s with empty strings.处理要编码的数据并用空字符串替换
None
会更好。 After all, that is what you want.毕竟,这就是你想要的。
Here is a slightly improved version that handles lists and tuples as well:这是一个稍微改进的版本,它也可以处理列表和元组:
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
I used it when using jsonschmea
module.我在使用
jsonschmea
模块时使用它。 It seems that it cannot handle None
type, and throws: jsonschema.exceptions.ValidationError: None is not of type u'string'
.似乎它无法处理
None
类型,并抛出: jsonschema.exceptions.ValidationError: None is not of type u'string'
。 So this takes care of the problem.所以这可以解决问题。
You can actually use the json.JSONEncoder , if you have an object with lists, tuples, dicts, strings and None, you can use the class shown afterwards to replace None to empty string.您实际上可以使用json.JSONEncoder ,如果您有一个带有列表、元组、字典、字符串和 None 的 object,您可以使用 class 来替换之后显示的空字符串。
default
is the method originally used to convert non json types to python, this time we use it to convert the None to empty string. default
是原先用于将非 json 类型转换为 python 的方法,这次我们使用它来将 None 转换为空字符串。
encode
is used to encode the json, that's why we use it with the new default to use the new method 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))
Then instead of dump, you use encode with the class然后代替转储,您使用 class 编码
NoneToEmptyJSON().encode(['foo', {'bar': ('baz', None, 1.0, 2)}])
Then the result is:那么结果是:
'["foo", {"bar": ["baz", "", 1.0, 2]}]'
You can also use params if you want indent or other things this way:如果你想要缩进或其他东西,你也可以使用 params :
NoneToEmptyJSON(ensure_ascii=False, indent=2).encode(['foo', {'bar': ('baz', None, 1.0, 2)}])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.