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.
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
It would be better to process the data you want to encode and replace None
s with empty strings. After all, that is what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With