简体   繁体   English

使用json解析空字符串

[英]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 using json.loads() you will have to use json.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM