Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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":""}
like image 894
apocalypsis Avatar asked Mar 07 '26 02:03

apocalypsis


1 Answers

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'}}
like image 54
jpp Avatar answered Mar 09 '26 14:03

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!