Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{"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!

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading