22

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?

1

3 Answers 3

41

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

Sign up to request clarification or add additional context in comments.

4 Comments

And even an updated version of simplejson would work as well.
That worked. Not sure why simplejson didn't do it. Any disadvantage in using json as opposed to simplejson in Django?
Ok - now simplejson seems to work to... Not sure whant was happeing but I was definitely getting None in my json dump yesterday
I've never run any benchmarks comparing them myself but at stackoverflow.com/questions/712791/… people are saying simplejson is faster. (And of course, if you need compatibility with Python 2.5 the built-in json module is out.)
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.

Comments

0

in JS create a variable None wich is null

let None = null;

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.