18

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?

Air
  • 8,274
  • 2
  • 53
  • 88
Darwin Tech
  • 18,449
  • 38
  • 112
  • 187
  • 5
    What version are you using of simplejson? According to the documentation, None should be converted to null automatically (see http://simplejson.googlecode.com/svn/tags/simplejson-2.0.9/docs/index.html) – Ian Hunter Mar 30 '12 at 16:56

2 Answers2

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]'

See http://docs.python.org/library/json.html

Richard Connamacher
  • 3,115
  • 19
  • 21
  • And even an updated version of simplejson would work as well. – jdi Mar 30 '12 at 17:04
  • That worked. Not sure why simplejson didn't do it. Any disadvantage in using json as opposed to simplejson in Django? – Darwin Tech Mar 30 '12 at 17:06
  • Ok - now simplejson seems to work to... Not sure whant was happeing but I was definitely getting None in my json dump yesterday – Darwin Tech Mar 30 '12 at 17:10
  • 2
    I've never run any benchmarks comparing them myself but at http://stackoverflow.com/questions/712791/json-and-simplejson-module-differences-in-python people are saying simplejson is faster. (And of course, if you need compatibility with Python 2.5 the built-in json module is out.) – Richard Connamacher Mar 30 '12 at 17:29
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.

Jipstuh
  • 41
  • 2