JSON parse - single quote inside name

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?

+7
source share
1 answer

I can imagine two possibilities:

Create a script element of type application/json , enter the template data into it, then read its data, for example.

 <script id="place-json" type="application/json"> {{place.json|safe}} </script> <script type="application/javascript"> P.place = $('#place-json').text(); </script> 

Or, to avoid single quotes before entering a string, for example.

 simplejson.dumps(yourdata).replace("'", r"\'") 
+8
source

All Articles