Render JSON as HTML Table and return as a webpage using Python Flask

Question:

I have write a movies recommendation and the function willreturn something like this. I am looking for away to convert this to HTML table and display as a webpage using Python Flask

[
    {
        "id": 601,
        "imdb_id": "tt0068646",
        "imdb_rating": "9.2",
        "language": "English, Italian, Latin",
        "poster": "https://m.media-amazon.com/images/M/MV5BM2MyNjYxNmUtYTAwNi00MTYxLWJmNWYtYzZlODY3ZTk3OTFlXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_SX300.jpg",
        "title": "The Godfather",
        "year": 1972
    },
    {
        "id": 603,
        "imdb_id": "tt0071562",
        "imdb_rating": "9.0",
        "language": "English, Italian, Spanish, Latin, Sicilian",
        "poster": "https://m.media-amazon.com/images/M/MV5BMWMwMGQzZTItY2JlNC00OWZiLWIyMDctNDk2ZDQ2YjRjMWQ0XkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_SX300.jpg",
        "title": "The Godfather Part II",
        "year": 1974
    },
    {
        "id": 622,
        "imdb_id": "tt0108052",
        "imdb_rating": "9.0",
        "language": "English, Hebrew, German, Polish, Latin",
        "poster": "https://m.media-amazon.com/images/M/MV5BNDE4OTMxMTctNmRhYy00NWE2LTg3YzItYTk3M2UwOTU5Njg4XkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_SX300.jpg",
        "title": "Schindler's List",
        "year": 1993
    }
]

I did try with json2html but it doesn’t work at all

Asked By: Phuc

||

Answers:

I don’t know what your problem is with json2html but this code worked for me.

from json2html import json2html

htmlJson = json2html.convert(json)

You can style the table with the argument table_attributes.

If it still doesn’t work, I give you this script, but my recommendation is the library.

def createColumn(dataMovie,tag):
    return f'<tr>'+f''.join([f'<{tag}>{value}</{tag}>' for value in dataMovie])+f'</tr>'

dataColumns = ''.join(map(lambda it:createColumn(it.values(),'td'),json))

titleColumn = createColumn(json[0].keys(),'th')

htmlJson = '<table>'+titleColumn+dataColumns+'</table>'

If you need more information about json2html here is the documentation

Answered By: Josephdavid07
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.