Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

385
Views
In Django how to pass JSON data to use for Ajax / jQuery?

I'm trying to use JSON data in Django to provide user option to search and select. I can load and extend data to html but not sure how to use it in jQuery. My code works just fine if I link my jQuery to some website outside my server. I mean if I can link it like that:

$.getJSON("http://meme.computer/stack/data.json", function(data) {

My code is:

views.py:

from django.shortcuts import render
from aceform.forms import RequestForm
import json

def index(request):
    form = RequestForm()
    data = open('data.json').read()
    jsonData = json.dumps(data)
    return render(request, 'aceform/base.html', {'form': form, 'jsonData': jsonData})

base.html:

{% load staticfiles %}

<!doctype html>
<html>
    <head>
      <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      <script>
     $(function() {
        var data = JSON.parse("{{ jsonData }}");
        console.log(data)
        autoComplete = [];
            for (var i = 0, len = data.length; i < len; i++) {
                autoComplete.push(data[i].iata + ", " + data[i].name);
            }
            console.log(data);
            $( "#id_from_airport" ).autocomplete({
                source: autoComplete,
                minLength: 3
            });
            $( "#id_to_airport" ).autocomplete({
                source: autoComplete,
                minLength: 3
            });
     });
    </script>
    </head>

    <body>
        {% block content %}

        {{ form.as_p }}

        {% endblock content %}
    </body>
</html>
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

$.getJSON("{{jsonData}}", function(data)

Doesn't make sense. You are calling getJSON on rendered JSON from your view. You already have the data in your template.

Depending on what template engine you are using, you should just be able to iterate over your {{jsonData}}.

about 4 years ago · Santiago Trujillo Report

0

At this point here:

data = open('data.json').read()

data is already of type string.

You don't need to "turn this into json" because it's already serialized (hopefully) as json.

You can do this to prove it to yourself (and maybe check for errors along the way):

def index(request):
    form = RequestForm()
    data = open('data.json').read()
    jsonData_loaded = json.loads(data)
    jsonData = json.dumps(jsonData_loaded)
    # I note here that you aren't closing the open file data.
    return render(request, 'aceform/base.html', {'form': form, 'jsonData': jsonData})

But that would be super silly.

It might make more sense to just do:

def index(request):
    form = RequestForm()
    with opened as open('data.json'):
        data = json.load(opened)
    jsonData = json.dumps(data)
    return render(request, 'aceform/base.html', {'form': form, 'jsonData': jsonData})

I mean, it's probably also redundent to load and dump, but a.) how do you know that json on disk is valid and b.) you might carry over new line charectors or other random crap.

(I wouldn't read from disk like that anyway for this kind of thing)

The moral of the story here is, you already have a string. You could just pass it along and hope for the best on the FE side!

Edit for FE:

Oh, and then I just looked at your template.

You don't actually need the whole $.getJSON function because you already have json.

You can just do var data = JSON.parse('{{jsonData|safe}}');

and then go to town with that!

about 4 years ago · Santiago Trujillo Report

0

You can use a safe tag to pass json data to js/jquery,just like {{ jsonData|safe }}

I see your jsonData is already a string of the format of json.

You can try this in your template like

<script>
    $(function () {
        var data = {{ jsonData|safe }}
        console.log(data)
        autoComplete = [];
        for (var i = 0, len = data.length; i < len; i++) {
            autoComplete.push(data[i].iata + ", " + data[i].name);
        }
        console.log(data);
        $("#id_from_airport").autocomplete({
            source: autoComplete,
            minLength: 3
        });
        $("#id_to_airport").autocomplete({
            source: autoComplete,
            minLength: 3
        });
    });
</script>
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!