Converting JSON to HTML table in Python
57,402
Solution 1
Try the following:
infoFromJson = json.loads(jsonfile)
print(json2html.convert(json = infoFromJson))
The result from json2html.convert
is a string.
If you don't have json2html module:
$ pip install json2html
More examples here.
Solution 2
Nowadays it's better to use json2table (at least for Python 3)
import json2table
import json
infoFromJson = json.loads(jsonfile)
build_direction = "LEFT_TO_RIGHT"
table_attributes = {"style": "width:100%"}
print(json2table.convert(infoFromJson,
build_direction=build_direction,
table_attributes=table_attributes))
Author by
OMGitzMidgar
Updated on January 18, 2022Comments
-
OMGitzMidgar over 2 years
I've been using the JSON library for Python to get data from JSON files using Python.
infoFromJson = json.loads(jsonfile)
I fully understand how to work with JSON files in Python. However, I am trying to find a way to format JSON format in a nice way.
I prefer to convert the JSON into a nested HTML table format.
I found json2html for Python, which does exactly what I just described. However, it does not actually output anything when I run the script they provide.
Has anyone had experience with this tool? Or does anyone have suggestions for alternatives?
-
OMGitzMidgar almost 9 yearsThis works, thank you! For some reason, if I try to combine the two lines you provided into one line, it does not print out anything (including no errors). Thanks for the help!
-
Kyle Shrader almost 9 yearsI doubt it's a naming/scope issue, but does it work in a single line if you alias the import for json to a different name?
-
OMGitzMidgar almost 9 yearsSorry, can you further explain what you mean by "aliasing the import for json to a different name" ?
-
Kyle Shrader almost 9 yearsThe issue you're seeing while doing this in one line might be the fact that the json library and the json default parameter are named similarly. But i have no idea :P
import json as jason; print json2html.convert(json = jason.loads(jsonfile)
none the less, glad it works. ^_^ -
mit almost 5 yearsI tried out both json2html and json2table with python 3 and had some issues with json2table using complex json structures. I am going with json2html and can't see why I shouldn't. Code looks ok and project is maintained.
-
Robert Lugg almost 5 yearsAt least for me, it looks like
import json2html
andjson2html.json2html.convert
-
SBDK8219 about 4 yearsIs it possible to make some fields editable by changing the
table_attributes
inson2html.convert()
function? -
Constantine Kurbatov over 2 yearsIt is recommended to use the following way to import:
from json2html import *
-
Constantine Kurbatov over 2 yearsThis version is good as has more flexibility in formatting.