I've been dealing with JSON data in Django view and parsing it in JavaScript to extract the necessary information.
This is a snippet from my view.py file (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 output of the ibm
variable in the Django template is:
[{"numeroIbm": "AUTO P"}, {"numeroIbm": "PTB"}, {"numeroIbm": "FAROL"}]
This is part of my index.html file (JS code embedded)
{{ ibms|json_script:"ibms" }}
<script>
const mydata = JSON.parse(document.getElementById("ibms").textContent);
const mydata2 = JSON.parse(mydata);
</script>
The issue I'm facing is that I have to use JSON.parse
twice to obtain the JavaScript object. The variable mydata
, despite being parsed, remains in string format. The desired result is achieved only after the second parsing (mydata2
).
Could someone please explain what might be causing this?
Thanks in advance!