json 如何将 None 转储为空字符串

新手上路,请多包涵

我希望 Python 的 None 在 json 中编码为空字符串如何?以下是 json.dumps 的默认行为。

 >>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'

我应该覆盖 json 编码器方法还是有其他方法?

输入数据不像上面的例子那么简单,在每次请求时它都可以更改为不同的数据结构。很难编写用于更改数据结构的函数。

原文由 Ahsan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

在您正在编码的对象中,使用空字符串代替 None

这是一个未经测试的函数,它通过一系列嵌套字典将所有 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

原文由 Noufal Ibrahim 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是一个稍微改进的版本,它也可以处理列表和元组:

 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' 。所以这解决了这个问题。

原文由 radtek 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题