In a Django view I am generating a data set something like this:
data = [22, 23, 18, 19, 21, None, 22, 20]
I am passing this data to a JavaScript variable using:
data_json = simplejson.dumps(data)
For use in a High Charts script.
Unfortunately JavaScript is stumbling when it encounters the None
value because actually what I need is null
. How can I best replace None
with null
, and where should I handle this - in the Django View or in the JavaScript?
Use the boolean OR operator to convert None to an empty string in Python, e.g. result = None or "" . The boolean OR operator returns the value to the left if it's truthy, otherwise the value to the right is returned. Since None is a falsy value, the operation will return "" . Copied!
The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.
There's no null in Python; instead there's None . As stated already, the most accurate way to test that something has been given None as a value is to use the is identity operator, which tests that two variables refer to the same object.
There is no NULL in Python. Instead, it has None. JSON has a NULL data type, but it has not a None data type. A dictionary in Python cannot have null as a value but can have “null” as a value that can be interpreted as a string.
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]'
See http://docs.python.org/library/json.html
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