Alejandro Veintimilla
Alejandro Veintimilla

Reputation: 11573

Django. Use Json file from context variable in Jquery

I want to pass a list to Jquery and then use it with the Autocomplete jqueryui widget. It is a small list, so I don't think I need a new request. So, I guess I don't need to use Jsquery's getJSON.

I have:

 json_list = json.dumps(list)
 context = {'json_list':json_list}
 return render(request, template, context)

in jquery:

var json_list = JSON.parse({{json_list}});
$("#field").autocomplete({
  source: json_list
 });

I get a Syntax Error on "&quot":

 var autores_json = JSON.parse(["Friedrich Hayek", "Milton Friedma...

Im kind of lost here. Any help will be appreciated.

Upvotes: 0

Views: 673

Answers (2)

elzi
elzi

Reputation: 5692

JSON.parse() need a string, so add some quotes.

Second, it's having trouble with HTML entities. After ensuring json_list is a string, use

JSON.parse(json_string.replace(/"/g,'"'));

EDIT: As mentioned above, better to pass safe in then use regex.

Upvotes: 0

Grisha S
Grisha S

Reputation: 838

Forgot the quotes.

var json_list = JSON.parse('{{json_list}}');
$("#field").autocomplete({
  source: json_list
 });

Also, I'm not sure whether it will recognize " as a quote char, so maybe you should try:

var json_list = JSON.parse('{{json_list|safe}}');
$("#field").autocomplete({
  source: json_list
 });

Upvotes: 2

Related Questions