Skip to content
Advertisement

Passing JSON data from Flask to JavaScript

I am trying to pass a JSON data from flask to JavaScript.

The code I tried is from:


The steps below are what I did :

  1. I first got my data from postgreSQL in Python
  2. I transformed the data format from DataFrame to JSON
    
def to_json2(df,orient='split'):
    df_json = df.to_json(orient = orient, force_ascii = False)
    return json.loads(df_json)


def to_fronrend(data):
    return {"data": data}

json2 = to_json2(df)
json2 = to_fronrend(json2) 
  1. I modified @Ilya V. Schurov’s code
app = Flask(__name__)

@app.route('/')

def hello_world():
    data = json2
    return render_template("index.html", data = data)

app.run()

And this is my index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> Hello </title>
</head>
    
<body>
    <p>Hello, <span id="username"></span></p>
    
    <script>
    var data = JSON.parse('{{ json2 | tojson | safe}}');
    document.getElementById('username').innerHTML = data.Name + " " + data.Gatein;
    </script>

    
    </body>
</html>

However, it kept showing the error

TypeError: Object of type Undefined is not JSON serializable
127.0.0.1 - - [18/Dec/2020 22:14:14] "GET / HTTP/1.1" 500 -

And the webpage(http://127.0.0.1:5000/) showing:

Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

I spent almost 2 days on this problem, passing the json data to the JavaScript, but still don’t know how to solve this… Could anyone give me some suggestion on this?

Advertisement

Answer

In the template, you are using the variable json2:

{{ json2 | tojson | safe}}

but, when rendering, you are passing in variable data:

return render_template("index.html", data=data)

Replace json2 with data in your template:

{{ data | tojson | safe }}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement