In Django template I have printed out data like this:
P.place = '{{place.json|safe}}';
Then in JavaScript file I'm paring it like that:
place = JSON.parse(P.place);
Everything is fine for data like that:
{"category": "Cars", "name": "Z"}
Because string looks like that:
P.place = '{"category": "Cars", "name": "Z"}'
So, I can parse it using JSON.parse method witch accept strings as input.
Problem is when I get data like that:
{"category": "Cars", "name": "Wojtek's Z"}
Because than input string for JSON parser looks like that:
'{"category": "Cars", "name": "Wojtek'
I cannot escape single quote inside JSON string, because then JSON string become invalid. From the same reason I cannot replace surrounding quotes by double and escape double quotes inside JSON string.
My solution looks like that:
In HTML template:
P.place = {{place.json|safe}};
Then in JavaScript
var place = JSON.stringify(P.place);
place = JSON.parse(place);
It works, but it is not optimal solution IMHO.
How to solve this problem in more cleaver way?
I can think of two possibilities:
Create a script element of type application/json
, inject your template data into it, then read its data, eg.
<script id="place-json" type="application/json">
{{place.json|safe}}
</script>
<script type="application/javascript">
P.place = $('#place-json').text();
</script>
Or, manually escape the single quotes before injecting the string, eg.
simplejson.dumps(yourdata).replace("'", r"\'")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With