1

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"}]"
1
  • How do you print the data? Commented Aug 9, 2021 at 16:41

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Can't you omit the json.dumps(json.loads(...)), and thus work with "data": data?
i has been tried and doesn't it worked, and now work, tks
but normally dumps and loads are each other's inverse. So if both are removed, then one would expect that simply passing the data without any dumps/loadss would produce the same data.
this make sense now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.