How json dumps None to empty string

json, python

Solution

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

Problem

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.

Original source