使用json解析空字符串 [英] parse empty string using json
本文介绍了使用json解析空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有一种方法可以使用json.loads
来自动将空字符串转换为其他内容,例如None
.
I was wondering if there was a way to use json.loads
in order to automatically convert an empty string in something else, such as None
.
例如,给定:
data = json.loads('{"foo":"5", "bar":""}')
我想拥有:
data = {"foo":"5", "bar":None}
代替:
data = {"foo":"5", "bar":""}
推荐答案
您可以使用字典理解:
data = json.loads('{"foo":"5", "bar":""}')
res = {k: v if v != '' else None for k, v in data.items()}
{'foo': '5', 'bar': None}
这只会处理嵌套字典的第一级.您可以使用递归函数来处理更广义的嵌套字典情况:
This will only deal with the first level of a nested dictionary. You can use a recursive function to deal with the more generalised nested dictionary case:
def updater(d, inval, outval):
for k, v in d.items():
if isinstance(v, dict):
updater(d[k], inval, outval)
else:
if v == '':
d[k] = None
return d
data = json.loads('{"foo":"5", "bar":"", "nested": {"test": "", "test2": "5"}}')
res = updater(data, '', None)
{'foo': '5', 'bar': None,
'nested': {'test': None, 'test2': '5'}}
这篇关于使用json解析空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文