loop in json in flask using render_template

Asked

Viewed 63 times

0

Hello, I have the following json:

{"movies": "[{\"title\":\"Hercules\",\"rep\":99.96},{\"title\":\"In the Dark\",\"rep\":98.12},{\"title\":\"Titas\",\"rep\":96.61}]"}

and would like to scroll through it playing in a table in html using the flask render template, stayed that way:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>

    <div>
      <h1>Flask</h1>

      <table>
        <thead>
          <tr>
            <th>Título</th>
            <th>Rep</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {% for movie in movies %}
          <tr>
            <td>{{ movie.title }}</td>
            <td>{{ movie.rep }}</td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
      
</body>

</html>

but I have as a result the following: inserir a descrição da imagem aqui

Note: json was generated via a dataframe using the following code:

m = df[['title','rep']].head(3).to_json(orient='records')
movies={'movies':m}
return render_template('index.html',movies=json.dumps(movies))

what I’m doing wrong?

1 answer

0

The first problem is that you are passing one string for the method render_template when using the json.dumps. You also do not need to convert the dataframe to json and then in dictionary, give to use the method to_dict.

Also you could pass the list directly in the parameter, you wouldn’t need to add it to a dictionary.

So, this way your template should work as expected:

movies = df[['title','rep']].head(3).to_dict(orient='records')
return render_template('index.html', movies=movies)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.