In the Django template, I printed the following data:
P.place = '{{place.json|safe}}';
Then in the JavaScript file I process it like this:
place = JSON.parse(P.place);
Everything is good for data:
{"category": "Cars", "name": "Z"}
Since the line looks like this:
P.place = '{"category": "Cars", "name": "Z"}'
So, I can parse it using the JSON.parse method, which takes strings as input.
The problem is when I get this data:
{"category": "Cars", "name": "Wojtek Z"}
Because the input line for the JSON parser looks like this:
'{"category": "Cars", "name": "Wojtek'
I cannot escape the single quote inside the JSON string, because the JSON string is getting invalid. For the same reason, I cannot replace surrounding quotes with double and avoid double quotes inside a JSON string.
My solution looks like this:
In the HTML template:
P.place = {{place.json|safe}};
Then in javascript
var place = JSON.stringify(P.place); place = JSON.parse(place);
This works, but this is not an optimal IMHO solution.
How to solve this problem in a more flexible way?