-2

I am currently working on a python bottle app and have built an array like the one below in Python.

[{'text': 'aampm', 'size': 1}, {'text': 'absolutely', 'size': 1},...

I added this to a json object using json.dumps() and then trying to pass the value to the front end using template like the following:

return template('example',
                word_cloud = word_cloud)

Within the javascript area, I load the file using the following:

var cloud = JSON.parse({{word_cloud}});

But I am getting an issue because it is returning the list like this and replace the "'" with """.

var cloud = JSON.parse([{"text": "aampm", "size": 1}, {"text"

How do I make it so that it loads in the right format -

([{'text': 'word', 'size': 5}, {'text': 'cloud', 'size': 15}])
  • 1
    Is the statement `var cloud = JSON.parse({{word_cloud}});` being rendered as part of a Jinja2 template? If so you may need to filter it using the [`safe`](http://jinja.pocoo.org/docs/2.9/templates/#working-with-automatic-escaping) filter (i.e. `{{ word_cloud | safe }}`). – metatoaster Mar 06 '17 at 08:59
  • That's not "the right format". JSON uses doble quotes as string delimiters. – Stop harming Monica Mar 06 '17 at 09:16
  • I am trying to build a word cloud and it needs the input to be in the format in the third code set - ([{'text': 'word', 'size': 5}, {'text': 'cloud', 'size': 15}]). I am making a bottle app and passing to the javascript section using {{value}}. I tried the {{word_cloud | safe}} and still getting the following - var cloud = JSON.parse([{"size": 1, "text": "aampm"}, {"size": 1,... – Ryan Kramer Mar 07 '17 at 09:04
  • I have added the project to GitHub. It might make it a little easier to show what I am doing and the issue I am facing. https://github.com/RyanKramer/TwitterAnalytics – Ryan Kramer Mar 07 '17 at 09:09
  • specifically, it would be in /html/example.html and the code that returns the template would be on lines 271 and 272 in TwitterAnalytics.py – Ryan Kramer Mar 07 '17 at 09:38

1 Answers1

0

let's rewrite your code in views.py

from django.http import JsonResponse

def your_function(request):
    result = [{'text': 'aampm', 'size': 1}, {'text': 'absolutely', 'size': 1},...
    return JsonResponse(result, safe = False, status = 200)

This will give you your expected response.

subha.py
  • 463
  • 3
  • 18
  • This is a bottle app. I am not sure if this will work unless recreate the app as a django app. – Ryan Kramer Mar 07 '17 at 09:05
  • then I completely missed it. Anyway If you recreate it in Django you can use this. – subha.py Mar 07 '17 at 09:32
  • Thanks. As a last resort I may do this but for now, I think it would be an easy fix once I find the actual fix :). I added GitHub details above if you want to see what I am doing specifically. – Ryan Kramer Mar 07 '17 at 09:40