title: Going from PostgreSQL JSONField to JSON object in Django template
body: <p>I am trying to send a JSON object from a Django PostgreSQL database to a Django template. Here is my models.py</p>
  
  <pre><code># models.py
  from __future__ import unicode_literals
  
  from django.contrib.postgres.fields import JSONField
  
  from django.db import models
  
  class Net(models.Model):
      net_name = models.CharField(max_length=200)
  
      def net_default():
          return {"net_name": "None", "graph_data": "None", "city_data": "None"}
  
      data = JSONField(default=net_default())
  
      def __unicode__(self):
          return self.net_name
  </code></pre>
  
  <p>Here is my views.py</p>
  
  <pre><code># standard includes
  from django.shortcuts import render
  
  # my includes
  from django.http import HttpResponse
  from django.template import loader
  
  # get nets
  from .models import Net
  
  def index(request):
      net_q_set = Net.objects.order_by('net_name')
      context = {
          'nets': net_q_set,
      }
      return render(request, 'viewer/index.html', context)
  </code></pre>
  
  <p>So I have a sidebar in which the user selects a network from the 'nets' JSON object. Then a javascript function which takes the selected network name should iterate through the JSON object to get the network's nodes and get each node's latitude and longitude. I am able to iterate through the names with the following code (this code works and produces what I want):</p>
  
  <pre><code>{% for name in nets %}
      &lt;li&gt;&lt;a href="javascript:plotMap('{{name}}');"&gt;{{name}}&lt;/a&gt;&lt;/li&gt;
  {% endfor %}
  </code></pre>
  
  <p>But I am having an issue establishing the JSON object in the javascript script. I have tried:</p>
  
  <pre><code>&lt;script&gt;
      var nets = JSON.parse({{ nets }})
      function plotMap(name){ ... };
  &lt;/script&gt;
  </code></pre>
  
  <p>But I get an error of 'unexpected token &amp;' on the <code>var nets</code> line. I am guessing this is from parsing the JSON object. Is there a better way to do this? Or am I making an error I am blind to?</p>
  
  <p><strong>Edit -- 2</strong> Using @Arpit's solution, I call </p>
  
  <pre><code>{% for name in nets %}
      &lt;li&gt;&lt;a href='javascript:plotMap({{name.data}});'&gt;{{name}}&lt;/a&gt;&lt;/li&gt;
  {% endfor %}
  </code></pre>
  
  <p>Then in the <code>plotMap(net_json)</code> function I immediately call <code>alert(net_json.city_data.Perth1.lat);</code> from my understanding this should make an alert that displays "-31.93333", instead I get an error "Uncaught SyntaxError: Unexpected string". Clicking the debugger link on that shows me:</p>
  
  <p><code>plotMap({u'city_data': {u'Alice,Springs': {u'lat': -23.7, u'long': 133.88333}, ...}, u'graph_data': {u'nodes': [u'Perth1', ...], u'links': [[u'Perth1', u'Adelaide1'], ...]'});</code></p>