[英]parse empty string using json
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
. 我想知道是否有一种使用
json.loads
的方法来自动将空字符串转换为其他值,例如None
。
For example, given: 例如,给定:
data = json.loads('{"foo":"5", "bar":""}')
I would like to have: 我想拥有:
data = {"foo":"5", "bar":None}
Instead of: 代替:
data = {"foo":"5", "bar":""}
You can use a dictionary comprehension: 您可以使用字典理解:
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'}}
You can also accomplish this with the json.loads
object_hook
parameter. 您也可以使用
json.loads
object_hook
参数来完成此object_hook
。 For example: 例如:
import json
import six
def empty_string2none(obj):
for k, v in six.iteritems(obj):
if v == '':
obj[k] = None
return obj
print(json.loads('{"foo":"5", "bar":"", "hello": {"world": ""}}',
object_hook=empty_string2none))
This will print 这将打印
{'foo': '5', 'bar': None, 'hello': {'world': None}}
This way, you don't need additional recursion. 这样,您不需要其他递归。
I did some trial and error and it is impossible to parse
None
into a String usingjson.loads()
you will have to usejson.loads() with json.dumps()
like I do in this example:我做了一些试验和错误,并且无法使用
json.loads()
将None
解析为字符串,您将不得不像在本示例中一样将json.loads() with json.dumps()
使用:
import json
data = json.loads('{"foo":"5", "bar":"%r"}' %(None))
data2 = json.loads(json.dumps({'foo': 5, 'bar': None}))
if data2['bar'] is None:
print('worked')
print(data['bar'])
else:
print('did not work')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.