在 Python 中将 JSON 转换为 HTML 表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31011179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:20:13  来源:igfitidea点击:

Converting JSON to HTML table in Python

pythonhtmljsonhtml-tablejson2html

提问by OMGitzMidgar

I've been using the JSON library for Python to get data from JSON files using Python.

我一直在使用 Python 的 JSON 库来使用 Python 从 JSON 文件中获取数据。

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.

我完全理解如何在 Python 中处理 JSON 文件。但是,我试图找到一种以一种很好的方式格式化 JSON 格式的方法。

I prefer to convert the JSON into a nested HTML table format.

我更喜欢将 JSON 转换为嵌套的 HTML 表格格式。

I found json2htmlfor Python, which does exactly what I just described. However, it does not actually output anything when I run the script they provide.

我找到了 Python 的json2html,它完全符合我刚才描述的功能。但是,当我运行他们提供的脚本时,它实际上并没有输出任何内容。

Has anyone had experience with this tool? Or does anyone have suggestions for alternatives?

有没有人有使用这个工具的经验?或者有人对替代方案有什么建议吗?

采纳答案by Kyle Shrader

Try the following:

请尝试以下操作:

infoFromJson = json.loads(jsonfile)
print json2html.convert(json = infoFromJson)

The result from json2html.convertis a string.

结果来自json2html.convert一个字符串。

If you don't have json2htmlmodule:

如果您没有json2html模块:

$ pip install json2html

More examples here.

更多例子在这里

回答by Vedanta6

Nowadays it's better to use json2table (at least for Python 3)

现在最好使用 json2table (至少对于 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))