Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Python None to JavaScript null

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?

like image 702
Darwin Tech Avatar asked Mar 30 '12 16:03

Darwin Tech


People also ask

How do you convert None to null in Python?

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!

What is the equivalent of None in JavaScript?

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.

Is None null in Python?

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.

Is null in JSON None in Python?

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.


1 Answers

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

like image 128
Richard Connamacher Avatar answered Sep 30 '22 13:09

Richard Connamacher