Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to retrieve Django list as array in Javascript

I’m sending django list from view.py to my javascript. But when I receive the list in javscript, it only return me as string. I tried to print the type of the variable but it show me false which mean its not array list. So how can I retrieve the list as array in Javascript?

View.py

    mergedCompare = [item_listAssigned[f'subject{i}'] + ': ' + item_listAssigned[f'serial{i}'] for i in range(1, len(item_listAssigned) // 2 + 1)]
            global context
            context = {
                'mergedCompare': mergedCompare
            }


mergedCompare = ['EMP004: BPCE-RNHC-25G8', 'EMP003: 8FIW-9JRB-NY4J', 'EMP005: 7QF2-6HI9-XKZZ', 'EMP002: SG8P-YQKG-ZV3C', 'EMP001: PBF7-WZHT-WPZR']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

JavaScript:

        var assignedDevices = "{{mergedCompare|safe}}"
        const list = assignedDevices;
        console.log(Array.isArray(list)) //false , not array

>Solution :

You can render the JSON content as a JavaScript script with the |json_script template filter [Django-doc]. Then you can load the JSON blobk with JSON.parse(…):

{{ mergedCompare|json_script:"mergedCompare" }}

<script>
var assignedDevices = JSON.parse(document.getElementById('mergedCompare').textContent);
const list = assignedDevices;
console.log(Array.isArray(list))
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading