Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON parse - single quote inside name

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?

like image 250
Wojciech Bednarski Avatar asked Nov 04 '11 16:11

Wojciech Bednarski


1 Answers

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"\'")
like image 186
Moishe Lettvin Avatar answered Sep 28 '22 06:09

Moishe Lettvin