1

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?

  • `var received_data = {{ pr_colors }}` should work. [JSON](https://en.wikipedia.org/wiki/JSON) is called that because it can be used as-is in your code. You inserted it as a string. Not sure where the `&` came from though. In theory, wrapping it in quotes and parsing the string would work, but you have to wrap it in single quotes in that case, given that JSON uses double quotes. –  Mar 03 '22 at 19:42
  • 1
    Duplicate: [Django: passing JSON from view to template](https://stackoverflow.com/questions/31151229/django-passing-json-from-view-to-template) –  Mar 03 '22 at 19:46
  • it works, but only for the whole json. I try to access any element I get undefined. If I try to access by position[1], [2], etc.. I get letter by letter as output – Pedro Cury Mar 03 '22 at 19:47
  • What you describe happens if you access an unparsed string. It has String properties like .length, and using indexes returns letters. Don't use quotes. Use `var received_data = {{ pr_colors }}` or, if you want less performance: `var received_data = JSON.parse('{{ pr_colors }}')` –  Mar 03 '22 at 19:48
  • It doesn't accept var received_data = {{ pr_colors }} without quotes. I had already checked this post you mentioned before, but still no success.. I don't understand why the down vote. But anyway. tks for your help – Pedro Cury Mar 03 '22 at 20:03
  • What do you mean, "it doesn't accept"? Are you getting errors? Did you try `var received_data = {{ pr_colors | safe }}`? –  Mar 03 '22 at 20:12
  • Yes. if I use `var received_data = {{ praga_colors }}` I get Property assignment expected. – Pedro Cury Mar 03 '22 at 20:16
  • with `var received_data = {{ pr_colors | safe }}` I get Property assignment expected, ',' expected – Pedro Cury Mar 03 '22 at 20:20
  • 1
    1. use a short example JSON url like https://jsonplaceholder.typicode.com/users/1 2. use `var received_data = {{ pr_colors | safe }}` 3. load the view in the browser, press Ctrl+U to look at the source and paste it into your question (when I do this using your code, the browser logs the user object to the console just fine) –  Mar 03 '22 at 22:11
  • @ChrisG .. Tks a lot. That did it! – Pedro Cury Mar 04 '22 at 12:15
  • Great, so given that you supposedly tried this before, what turned out to be the cause for the issue in the first place? –  Mar 04 '22 at 12:19

0 Answers0