Passing data to Google Charts with Django


This question has been asked but not answered like this one.

In my I have data pulled from MySQL, example of the array:

(Decimal('13'), Decimal('6'), Decimal('13'))
(Decimal('207'), Decimal('18'), Decimal('129'))
(Decimal('301'), Decimal('38'), Decimal('193'))
(Decimal('204'), Decimal('32'), Decimal('150'))
(Decimal('159'), Decimal('25'), Decimal('88'))

args = {'array':array}
return render_to_response('page2.html', args)

Trying to put it into Google Chart

function drawChart() {
    var djangoData = JSON.parse('{{ args }}');
    var data = google.visualization.arrayToDataTable(djangoData);

Also tried var djangoData = {{ array }};
Both with no luck!



return render_to_response('page2.html', {'array': json.dumps(array)})

Looks like it would work, except that the db produces incompatible type. Is there a way to do this without converting every item to int type. Or if there if there is a pythonic way to convert it?

Asked By: rodling



You should try this in (do not forget to add the import json):

array = [['X', 'Y', 'Z'], [1, 2, 3], [4, 5, 6]]
return render_to_response('page2.html', {'array': json.dumps(array)})

Then in the template use the raw value array without quotes:

var djangoData = {{ array|safe }};
var data = google.visualization.arrayToDataTable(djangoData);

EDIT: using a custom JSONEncoder to handle the Decimal type, stolen from this question:

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        return super(DecimalEncoder, self).default(o)

Then in the view:

array = [['X', 'Y', 'Z'], [Decimal('1'), Decimal('2'), Decimal('3')]]
return render_to_response('page2.html', {
    'array': json.dumps(array, cls=DecimalEncoder),
Answered By: Nicolas Cortot
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.