1

I am trying to create a simple Flask app where an array of integers is generated on the server and sent to the client. I want to view the array of integers in the console. Here is some sample (working) code in app.py:

from flask import Flask, render_template, request, url_for

import random, json

app = Flask(__name__)

@app.route('/',  methods=['GET'])
def form():
    json_helper = {}
    json_helper['randoms'] = [random.random() for _ in range(40)]
    json_object = json.dumps(json_helper)
    return render_template('sim0625.html', s_data=json_object)

if __name__ == '__main__':
  app.run(debug=True)

And here is a snippet of the Javascript frontend:

<script>

  var data_xyz = {{ s_data|tojson }};

  var JSONObject = JSON.parse({{data_xyz}});
  console.log(JSONObject.randoms);  

 </script>

Unfortunately, none of the javascript works on my webpage, and the error message shown is "Uncaught SyntaxError: Unexpected token u".

Can someone please explain how to fix this? Thanks. My guess is the JSON objects are becoming strings.

Note: The code from the front-end was adapted from this SO question: Extracting data from json object in jQuery or JS

Community
  • 1
  • 1
codersun3
  • 165
  • 2
  • 4
  • 13

1 Answers1

3

You're sending your JSON to the template through the variable s_data.

In the template, you're rendering that variable into a JavaScript variable called data_xyz. In the next line, you attempt to reference a Jinja variable instead of a JavaScript variable:

var JSONObject = JSON.parse({{data_xyz}});

Change that to:

var JSONObject = JSON.parse(data_xyz);
Celeo
  • 5,583
  • 8
  • 39
  • 41
  • Thank you!! One question: I thought that the json.dumps() method in my app.py was taking a string and converting it into a JSON object. Therefore, I thought that the client is receiving a JSON object from the server (not a string). If the client is indeed receiving a JSON object (and not a string), why are these two lines of code necessary? "var data_xyz = {{ s_data|tojson }}; var JSONObject = JSON.parse({{data_xyz}});" From what I understand, these two lines of code convert a string into a JSON object. – codersun3 Jun 29 '15 at 20:17
  • 1
    @codersun3 [json.dumps](https://docs.python.org/2/library/json.html#json.dumps): "*Serialize obj to a JSON formatted str*" – Celeo Jun 29 '15 at 20:28