12

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?

2 Answers 2

22

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 module:

$ pip install json2html

More examples here.

Sign up to request clarification or add additional context in comments.

7 Comments

This 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!
I 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?
Sorry, can you further explain what you mean by "aliasing the import for json to a different name" ?
The 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. ^_^
At least for me, it looks like import json2html and json2html.json2html.convert
|
3

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))

3 Comments

I 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.
This version is good as has more flexibility in formatting.
Only problem with json2html is that after you convert complex JSON into html, the final format is not readable by python FPDF.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.