Search code examples
javascriptpythonjsonflaskto-json

Python to Javascript JSON objects (Flask)


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


Solution

  • 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);