Want to pass json array as django variable inside javascript

Viewed 101

I have a json array and I want to pass this inside a javascript variable, inside the django template. I am able to access the variable inside django template {{variable}} . But not able to access this inside the javascript.This is my variable:

[
    
    {'Book ID': '1', 'Book Name': 'Challenging Times',
    
     'Category': 'Business', 'Price': '125.60'},
    
    {'Book ID': '2', 'Book Name': 'Learning JavaScript',
    
     'Category': 'Programming', 'Price': '56.00'}
    
]

I have used {{variable|safe}} inside the js but not working. Plz let me know where I am making the mistake.

1 Answers

You should use the json_script template filter to add your variable to the template in a format that can be loaded in your JS

{{ variable|json_script:"foo" }}

<script>
    const foo = JSON.parse(document.getElementById('foo').textContent);
</script>
Related