json_script Filter

Coding Most Useful

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

Documentation

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

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

Variable

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'
    ]
}

Template

{{ classes|json_script:'classdata' }}

Result

<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:

<ol>
  <script>
    const classes = JSON.parse(document.getElementById('classdata').textContent);
    pythonClasses = classes['Python'];
    for (pythonClass of pythonClasses) {
      document.write(`<li>${pythonClass}</li>`);
    }
  </script>
</ol>

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

Commentary


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 Oct. 30, 2022, 1:21 p.m. EST