BrettJ BrettJ - 3 years ago 91
Javascript Question

Passing a JSON object from Flask to JavaScript

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?

Answer Source

The below simple example should show how to get a Javascript object from your dict:

views.py

@app.route('/', methods=['GET','POST'])                                         
def index():                                                                    

    points = [{"lat": 43.8934276, "lng": -103.3690243},                         
              {"lat": 47.052060, "lng": -91.639868},                            
              {"lat": 45.1118, "lng": -95.0396}]                                

    return render_template("index.html", points=json.dumps(points)) 

index.html (some code removed for brevity)

  function initMap() {                                                      

    var map = new google.maps.Map(document.getElementById('map'), {         
      center: new google.maps.LatLng(43.8934276, -103.3690243),             
      zoom: 4                                                               
    });                                                                     

    var points = JSON.parse('{{ points|safe }}');                           
    var marker;                                                             

    for (var i = 0; i < points.length; i++) {                               

        marker = new google.maps.Marker({                                   
          position: new google.maps.LatLng(points[i].lat, points[i].lng),   
          map: map                                                          
        });                                                                 

    }                                                                       
  }   
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download