• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

167
Views
Passing Json from Django view to template Javascript

I'm trying to pass a json response from a view to javascript. For some reason I can't access any keys inside javascript. I can only access the whole json object, but none of the nested keys attached to it.

Json(simplified for the purpose of reading):

{
"protected": [
    {
        "category": "nmtd",
        "name": "NMTD",
        "userId": 257
    }
]

}

views.py:

def index(request):
request_pr = requests.get('https://endpoint-address', cookies = request.COOKIES)
pr_colors = json.dumps(request_pr.json())    
context = {        
    'pr_colors': pr_colors
}    
return render(request, 'index.html', context)

Javascript:

<script type="text/javascript">                    
    var received_data = "{{ pr_colors }}"
    console.log(received_data)
</script>

There are two different kinds of problems. If I set JSON.parse("{{ praga_colors }}") I get Uncaught SyntaxError: Unexpected token & in JSON at position 1

If I just try to access the element directly without JSON.parse() I get all the values as undefined.

If I try to access by position praga_colors[1], I get a letter by letter string.

What is the proper way to handle this?

almost 3 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error