简体   繁体   中英

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 .

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. 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:

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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