json_script Filter

Coding Most Useful

Argument: id (required) – the id to give to the rendered script element.


Outputs a Python object as JSON inside of a script element.

This is the safest way to include data to be used by JavaScript.


classes = {
    'Python': [
        'Intro Python', 'Advanced Python', 'Data Science', 'Django'
    'Databases': [
        'Intro PostgreSQL', 'Intro MySQL', 'Intro SQL Server', 'Intro Oracle'
    'Web': [
        'HTML', 'CSS', 'JavaScript'
    'XML': [
        'Intro XML'


{{ classes|json_script:'classdata' }}


<script id="classdata" type="application/json">{"Python": ["Intro Python", "Advanced Python", "Data Science", "Django"], "Databases": ["Intro PostgreSQL", "Intro MySQL", "Intro SQL Server", "Intro Oracle"], "Web": ["HTML", "CSS", "JavaScript"], "XML": ["Intro XML"]}</script>

You can then use another script element to consume this content:

    const classes = JSON.parse(document.getElementById('classdata').textContent);
    pythonClasses = classes['Python'];
    for (pythonClass of pythonClasses) {

You could (and probably should) point to an external JavaScript file rather than using embedded JavaScript.


Did we get something wrong? Is there a use case for the json_script filter that we should add? Please let us know.

Send Feedback

Official Documentation
This page last updated on April 19, 2020, 7:04 a.m. EST