1

I am afraid I don’t understand what "serializing" means. If someone can explain I’d be grateful. I am serializing a Django model in Json as explained in the Django Docs:

data = serializers.serialize("json", MyModel.objects.all())

In my HTML/JS I access the data as recommended:

{{ data|json_script:"data" }}
var myData = JSON.parse([document.getElementById('data').textContent]); 

But instead of being an Object myData is a string. So I guess somehow I serialize twice or something.

I found a solution, JSON.parse works as expected on my data now:

data = json.loads(serializers.serialize("json", CoursePage.objects.child_of(self).live().public()))

But I guess I still don’t understand the meaning of "serializing" properly. The Python docs say about json.loads(s): "Deserialize s (a str instance containing a JSON document). Why do I have to deserialize before JSON.parse works? The description for JSON.parse states: "The JSON.parse() method parses a JSON string"? Which I thought Djangos serializer would gave me in the first place. I am confused.

1

1 Answer 1

2

The json_script filter is for Python objects. But serialization is already the conversion of Python objects into JSON. So effectively you're converting it twice.

In your case I wouldn't bother with that filter. Just remove the json.loads and output the data directly where you need it:

var myData = JSON.parse("{{ data|safe }}"); 
Sign up to request clarification or add additional context in comments.

1 Comment

I tried that before. I read your comment on a similar question. But I am getting a syntax error: "missing ) after argument list". In my HTML {{ data|safe }} renders as expected.

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.