Skip to content
Advertisement

Trouble when parsing JSON string

I’m dumping JSON in Django view and then parsing JSON in JS to get the data.

My view.py (Django)

ibms = []
for i in range(2, 5):
    ibm = Mapa(i, wsMapa)
    ibms.append(ibm.__dict__)
ibms = json.dumps(ibms)

return render(request, 'mapas/index.html', {'ibms': ibms})

The ibm variable output in Django template is:

[{"numeroIbm": "AUTO P"}, {"numeroIbm": "PTB"}, {"numeroIbm": "FAROL"}]

My index.html (JS inside)

{{ ibms|json_script:"ibms" }}
<script>
    const mydata = JSON.parse(document.getElementById("ibms").textContent);
    const mydata2 = JSON.parse(mydata);
</script>

The issue is: I’m having to JSON.parse double times to get the JS object. The variable mydata, despite the JSON.parse, is string typeof. I only get the final result when I JSON.parse for the second time (mydata2).

What is happening, pls?

Tks in advance!

Advertisement

Answer

You should not dump it in the view, so:

ibms = [Mapa(i, wsMapa).__dict__ for i in range(2, 5)]

return render(request, 'mapas/index.html', {'ibms': ibms})

and thus parse it as:

{{ ibms|json_script:"ibms" }}
<script>
    const mydata = JSON.parse(document.getElementById("ibms").textContent);
    // no second parse
</script>
Advertisement