0

I'm sending JSON string from Django view to javascript file named idbop.js at the client side. I'm using the serializer in Django to convert query result in Django to JSON. Here is my code in views.py of Django

def index(request):
template='posts/index.html'
results=feed.objects.all()
jsondata = serializers.serialize('json',results)
context={
    'results':results,
    'jsondata':jsondata,
}
return render(request,template,context)

At client side, I'm accessing jsondata in javascript as follows:

var jsondata="{{jsondata}}".replace(/"/g,"\"");

Here jsondata is in string format. If I try to parse it using, var data = JSON.parse(jsondata); It is throwing an error:SyntaxError: JSON.parse: bad control character in string literal at line 1 column 344 of the JSON data I'm having whitespace at 344 in jsondata but that whitespace is inside the string of value. Here is my JSON string:

[
    {
        "model": "posts.feed",
        "pk": 1,
        "fields": {
            "author": "J Watson",
            "title": "Service Worker",
            "body": "A service worker is a type of web worker. It's essentially a JavaScript file that runs separately from the main browser thread, intercepting network requests, caching or retrieving resources from the cache, and delivering push messages.

Because workers run separately from the main thread, service workers are independent of the application they are associated with. This has several consequences:"
        }
    }]
Scorpionk
  • 418
  • 6
  • 13

2 Answers2

0

You can safely insert your javascript content into your template with either safe or escapejs builtins. With using safe:

var jsondata = {{ jsondata|safe }}

Or with using escapejs:

var jsondata = JSON.parse({{ jsondata|escapejs }})
alioguzhan
  • 7,657
  • 10
  • 46
  • 67
  • 1
    I found out the root cause of the problem. Thanks for answering though. I'll definitely look into escapejs. I'm still new to web development. :) – Scorpionk Apr 03 '18 at 19:38
  • Glad if you made it! But still, it might be better to use builtins instead of replacing characters inside of your data. Of course, if they solve your problem. But they usually do :) @Scorpionk – alioguzhan Apr 03 '18 at 19:41
  • 1
    Yeah. You are right. Also safe and esacpejs seems easier than writing replace() function. – Scorpionk Apr 03 '18 at 19:44
0

I think you can use safe built-in template filter on your {{jsondata}}. In your situation it should look like this:

var jsondata={{ jsondata | safe }}

T.Tokic
  • 1,264
  • 9
  • 10