Search code examples
djangodjango-viewssimplejson

DJANGO simplejson


Good afternoon..i have a model with a class like this:

class Reportage:
    def get_num(self):
        end_date = self.date.end_date
        start_date = self.date.start_date
        duration = time.mktime(end_date.timetuple()) - time.mktime(start_date.timetuple())
        delta_t = duration / 60
        num = []

        for t in range(0,duration,delta_t):
            start = t + start_date
            end = datetime.timedelta(0,t+delta_t) + start_date
            n_num = self.get_num_in_interval(start,end)
            num.append([t, n_num])
        return num

I want to serialize with simplejson the array num [] in the views.py for passing in a second moment this array to a jquery script to plot it in a graph.. what's the code to serialize that array..? I hope I was clear .. thanks in advance to all those who respond ..


Solution

  • Following @ninefingers' response. I think that your question is aimed on how to make that dumped json string available to a jQuery plugin.

    # views.py
    
    def my_view(request):
    # do stuff
    num = reportage_instance.get_num()
    num_json = simplejson.dumps(num)
    return render(request, 'template.html', {
      'num_json': num_json,
    })
    

    In your template, you make available that json obj as a Javascript variable

    # template.html
    
    <html>
    <body>
    <script>
    var NUM_JSON = {{num_json|safe}};
    myScript.doSomething(NUM_JSON);
    </script>
    </body>
    </html>
    

    Now you can call regular JS with the NUM_JSON variable.