Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

708
Views
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']

JavaScript:

        var assignedDevices = "{{mergedCompare|safe}}"
        const list = assignedDevices;
        console.log(Array.isArray(list)) //false , not array
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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>
over 4 years ago · Santiago Trujillo Report

0

Another few approaches in addition to previous answer:

  • using safe filter
# your view code
...
return render(request, 'some.html', context = {"my_list": ["item1", "item2"]})

# your template code
{{ my_list|safe }}.forEach  // array
  • dump to/from JSON
import json

# your view code
...
mylist = json.dumps(mylistraw)
return render(request, 'some.html', context = {"my_list": mylist})

# your template code
var mylist = JSON.parse("{{mylist}}")
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!