Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How json dumps None to empty string

Tags:

python

json

I want Python's None to be encoded in json as empty string how? Below is the default behavior of json.dumps.

>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'

Should I overwrite the json encoder method or is there any other way?

Input data is not that simple as in above example, on every request it could be changed to different data structure. Its difficult to write a function for changing data structure.

like image 842
Ahsan Avatar asked Jul 10 '12 10:07

Ahsan


2 Answers

In the object you're encoding, use an empty string instead of a None.

Here's an untested function that walks through a series of nested dictionaries to change all None values to ''. Adding support for lists and tuples is left as an exercise to the reader. :)

import copy

def scrub(x):
    ret = copy.deepcopy(x)
    # Handle dictionaries. Scrub all values
    if isinstance(x, dict):
        for k,v in ret.items():
            ret[k] = scrub(v)
    # Handle None
    if x == None:
        ret = ''
    # Finished scrubbing
    return ret
like image 126
Noufal Ibrahim Avatar answered Sep 28 '22 00:09

Noufal Ibrahim


It would be better to process the data you want to encode and replace Nones with empty strings. After all, that is what you want.

like image 21
Otto Allmendinger Avatar answered Sep 27 '22 23:09

Otto Allmendinger