Reputation: 43
I have a list of items and want to pass it to javascript array. Django version 2.2.3
In my views.py:
my_list = ["one", "two"]
context = {
'my_list ': json.dumps(my_list),
}
return render(request, 'my_template.html', context)
my_template.html
<script>
var my_array = JSON.parse("{{ my_list|safe }}")
document.write(my_array )
</script>
According to the answers in most topics, my code is valid, but it doesn't display any data.
Also tried:
<script>
var my_string = "{{my_list}}";
var my_array = my_string.split(',');
document.write(my_array)
</script>
In this case when i want to display it i get
[" one "
Upvotes: 4
Views: 1431
Reputation: 5405
In your case, that would look like this:
{{ my_list |json_script:"my_array" }}
You can then access it from your script with:
var myArray = JSON.parse(document.getElementById('my_array').textContent);
Upvotes: 2
Reputation: 106553
JSON string literals are enclosed in double quotes, so you should use single quotes around the JSON object instead in JavaScript to avoid conflicts:
var my_array = JSON.parse('{{ my_list|safe }}')
But then again like @NalinDobhal mentions in the comment, in most cases you can simply assign the JSON object to a JavaScript variable because JSON is designed to follow the syntax of JavaScript.
Upvotes: 1