32👍
✅
If you’re using Python 2.6 or later, you can use the built-in json module:
>>> import json
>>> json.dumps([1, 2, 3, None, 4])
'[1, 2, 3, null, 4]'
0👍
When I tried the accepted solution json.dumps()
returned NaN values rather than the null JavaScript is looking for. Therefore I found another solution that does not use json or simplejson packages. The following solution uses type checking of None in Django. The solution that inspired me can be found here.
I used it in my code as follows to populate a Javascript array correctly:
[
{% for val in data %}
{% if val is none %}
null,
{% else %}
{{ val }},
{% endif %}
{% endfor %}
],
The none object in Django will check the None value offered by python. It doesn’t seem to correctly handle np.NaN objects though.
Source:stackexchange.com