LucasBorges-Santos
LucasBorges-Santos

Reputation: 392

Django serialize object return array

Django serialize object return an array, and i cant get it in template with js

my view.py:

def MyExempleView(request):
    data = serializers.serialize("json", myModel.objects.all())
    context = {
        "data" : json.loads(data)
    }
    return render(request, 'consulta/myTemplateExemple.html', context=context)

my template:

{{ data|json_script:"data" }}

if ($("#data").length) {
    var data= JSON.parse(document.getElementById('data').textContent);
}

my result exemple:

"[{"key": "value"}, {"key2": "value2"}]"

Upvotes: 1

Views: 362

Answers (1)

LucasBorges-Santos
LucasBorges-Santos

Reputation: 392

i solved loading and dumping the json with python json:

in views:

"data" : data

and in js in template:

var data = JSON.parse(document.getElementById('data').textContent)
jsonResponse = JSON.parse(data)

Upvotes: 2

Related Questions