0

In the backend django I will return data to frond end as json, but in frondend there are many "null" value, and one solution is to change code to convert value None to empty string "" when create the value, but since there are many places, I'd like to write a customized encoding function to convert None to "" when dump the obj into string. I used the following class, but it doesn't work:

class PythonObjectEncoder(json.JSONEncoder):
    def encode(self, obj):
        if obj is None:
            obj = ''
        return json.JSONEncoder().encode(obj)

data = [1,2,3,None,
        [[[2],3],4]
        ]

j = json.dumps(data, cls=PythonObjectEncoder)

2 Answers 2

1

One way to do this is just to filter the json object beforehand. For example, with such function:

def fix_data(data):
    if type(data) is list:
        for i, e in enumerate(data):
            if e is None:
                data[i] = ''
            else:
                fix_data(e)

    elif type(data) is dict:
        for k, v in data.items():
            if v is None:
                data[k] = ''
            else:
                fix_data(v)

# Example:
data = ['1', None, '0', {'test' : None}]
fix_data(data)
print(data)
Sign up to request clarification or add additional context in comments.

Comments

0

It is not possible to tell the json decoder something like:

Please encode this piece of data but replace each occurence of None by an empty string instead of null.

The reason is that this mapping is defined in json.scanner and can not be altered.

However, if you know what your data look like before json-encoding. You can pre-process them before encoding. Here is a piece of code that matches your example:

import json

class CustomListEncoder(json.JSONEncoder):
    def encode(self, o):
        if not isinstance(o, list):
            raise TypeError("This encoder only handle lists")
        none_to_empty_str = map(lambda x: "" if x is None else x, o)
        return super().encode(list(none_to_empty_str))

json.dumps([1,2,None, [3, 4, 5]], cls=CustomListEncoder)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.