Python to Javascript JSON objects (Flask) [duplicate]

南楼画角 提交于 2021-01-28 08:11:48

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/31123800/python-to-javascript-json-objects-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!