Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a JSON object from Flask to JavaScript

Tags:

I'm having troubles getting a Flask/Python variable passed to Javascript.

Basically, I'm importing from MySQL and have tried rendering the return in three different ways.

  1. (43.8934276, -103.3690243), (47.052060, -91.639868), (45.1118, -95.0396) that is the output when my dict item has the following ran on it.

new_list = [tuple(d.values()) for d in MySQL_Dict] output = ', '.join('(' + ', '.join(i) + ')' for i in new_list)

This method is no good, but I added it for detail, it's not in the right format at all.

  1. I pass the python dict directly to the template which looks like this

({'lat': '43.8934276', 'lng': '-103.3690243'}, {'lat': '47.052060', 'lng': '-91.639868'}, {'lat': '45.1118', 'lng': '-95.0396'})

Then on the the template side I've tried the following JavaScript lines

 var other_coords = {{ MySQL_Dict|tojson }};   var other_coords = {{ MySQL_Dict|tojson|safe }};  var still_more = JSON.parse(other_coords); 

None of which work, together or separately.

  1. I've also tried sending the dictionary from the view using json_out = json.dumps(My_Dict) which does not work either.

This is all with the goal of getting the lat, lng coords from the MySQL DB to the Google Maps API script. The thing that is so confusing to me is that if I just paste the json.dump results from the view into the Google Maps script it works perfectly (after the quotes are removed) but if I use a variable it will not work for me. Does anyone have suggestions?

like image 507
BrettJ Avatar asked Feb 28 '17 03:02

BrettJ


People also ask

How can I pass data from Flask to JavaScript in a template?

To pass data from Python Flask to JavaScript in a template, we can use the tojson filter. to convert the geocode dictionary to JSON and assign it to myGeocode . And then we use myGeocode as an object within our JavaScript code.

Can JSON be converted to JavaScript?

JSON text/object can be converted into Javascript object using the function JSON. parse(). If we pass a invalid JSON text to the function JSON. parse(), it will generate error (no output is displayed when using in tag of HTML).

Can Flask render JavaScript?

To pass variables from Python Flask to JavaScript, we can call render_template with the data argument with the dictionary of data we want to pass to the template. to call render_template with the template file name and the data set to the data dict with the data we want to pass to the template.

Can JavaScript read JSON file?

How to Read a JSON File in JavaScript with the Fetch API. One standard method we can use to read a JSON file (either a local file or one uploaded to a server) is with the Fetch API. It uses the same syntax for both. The only difference would be the URL.


1 Answers

It seems that the currently accepted answer (by @BrettJ) has a possible security flaw in it: if the object we pass to javascript has some string with a single quote inside, this single quote will not be escaped by json.dumps, thus allowing to inject arbitrary code into javascript. It is better to use Flask's tojson() template filter, see the docs, as it makes proper escaping of all such characters (replace them with unicode codes).

Here is my solution:

view.py

from flask import Flask, render_template  app = Flask(__name__)  @app.route('/') def hello_world():     user = {'firstname': "Mr.", 'lastname': "My Father's Son"}     return render_template("index.html", user=user)  if __name__ == '__main__':     app.run() 

index.html

<p>Hello, <span id="username"></span></p> <script>     var user = JSON.parse('{{ user | tojson | safe}}');     document.getElementById('username').innerHTML = user.firstname + " " +             user.lastname; </script> 

Generated JS looks like:

var user = JSON.parse('{"firstname": "Mr.", "lastname": "My Father\u0027s Son"}'); 

which is perfectly safe. For example, if we'd use json.dumps-powered solution, we'd get

var user = JSON.parse('{"firstname": "Mr.", "lastname": "My Father's Son"}'); 

which is syntactically incorrect (to say the least).

like image 177
Ilya V. Schurov Avatar answered Sep 27 '22 21:09

Ilya V. Schurov