Skip to content

Instantly share code, notes, and snippets.

@ischurov
Created July 24, 2017 16:01
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ischurov/34fb9e3d2ccd7a177275adac98bde42b to your computer and use it in GitHub Desktop.
Save ischurov/34fb9e3d2ccd7a177275adac98bde42b to your computer and use it in GitHub Desktop.
pass object to javascript via json in flask
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello, World</title>
</head>
<body>
<p>Hello, <span id="username"></span></p>
<script>
var user = JSON.parse('{{ user | tojson | safe}}');
document.getElementById('username').innerHTML=user.firstname + " " +
user.lastname;
</script>
</body>
</html>
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
user = {'firstname': 'Harry', 'lastname': 'Potter'}
return render_template("index.html", user=user)
if __name__ == '__main__':
app.run()
@Koubae
Copy link

Koubae commented Nov 20, 2020

You save my day!!!! Thanks.

@devcoronel
Copy link

Thanks! You save my day (x2)

@RadNi
Copy link

RadNi commented May 7, 2021

Same here (x3)

@dedol
Copy link

dedol commented May 27, 2021

Thanks!

@jagtapazad
Copy link

for me it is showing this error TypeError: Object of type Undefined is not JSON serializable
What can I do for it?

@LS-Chi
Copy link

LS-Chi commented Aug 8, 2023

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment