7

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?

Wojciech Bednarski
  • 6,033
  • 9
  • 49
  • 73

1 Answers1

8

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"\'")
Moishe Lettvin
  • 8,462
  • 1
  • 26
  • 40