python - json2html,Python : json data not converted to html

标签 python html json json2html

我正在尝试使用 json2html 将 json 数据格式化为 html。 json 数据如下所示:

json_obj = [{"Agent Status": "status1", "Last backup": "", "hostId": 1234567, "hostfqdn": "test1.example.com", "username": "user1"}, {"Agent Status": "status2", "Last backup": "", "hostId": 2345678, "hostfqdn": "test2.example.com", "username": "user2"}]

正如帖子“json2html not a valid json list python”中已经报道的那样,为了使代码正常工作,json参数必须是字典而不是列表,所以我这样调用它:

json_obj_in_html = json2html.convert(json = { "data" : json_obj })

但是它不会将 json 数据格式化为 html,仅在字典的第一级 { "data": json_obj }:

print json_obj_in_html
<table border="1"><tr><th>data</th><td>[{"Agent Status": "status1", "Last backup": "", "hostId": 1234567, "hostfqdn": "test1.example.com", "username": "user1"}, {"Agent Status": "status2", "Last backup": "", "hostId": 2345678, "hostfqdn": "test2.example.com", "username": "user2"}]</td></tr></table>

请注意,在线转换工具提供了正确的输出:http://json2html.varunmalhotra.xyz/

<table border="1"><tr><th>data</th><td><ul><table border="1"><tr><th>Agent Status</th><td>status1</td></tr><tr><th>Last backup</th><td></td></tr><tr><th>hostId</th><td>1234567</td></tr><tr><th>hostfqdn</th><td>test1.example.com</td></tr><tr><th>username</th><td>user1</td></tr></table><table border="1"><tr><th>Agent Status</th><td>status2</td></tr><tr><th>Last backup</th><td></td></tr><tr><th>hostId</th><td>2345678</td></tr><tr><th>hostfqdn</th><td>test2.example.com</td></tr><tr><th>username</th><td>user2</td></tr></table></ul></td></tr></table>

非常欢迎任何帮助。

最佳答案

确保 json_obj 是对象数组而不是字符串 ( str )。

我将您的代码放入完整的示例中:

from json2html import *
json_obj = [{"Agent Status": "status1", "Last backup": "", "hostId": 1234567, "hostfqdn": "test1.example.com", "username": "user1"}, {"Agent Status": "status2", "Last backup": "", "hostId": 2345678, "hostfqdn": "test2.example.com", "username": "user2"}]
json_obj_in_html = json2html.convert(json = { "data" : json_obj })
print json_obj_in_html

使用Python 2.7json2html 1.0.1,这会导致以下结果: enter image description here

如果您收到类似结果

<table border="1"><tr><th>data</th><td>[{"Agent Status": "sta...

json_obj 很可能是 str 而不是对象数组。您可以通过插入类似

的语句来检查这一点
print type(json_obj)

jsonhtml.convert 之前。我假设 type(json_obj) 在您的情况下返回 <type 'str'>,这就是为什么 JSON 之类的字符串出现在您的 html 中。为了得到正确的结果,您必须以 type(json_obj) 返回 <type 'list'> 的方式修改代码。

关于python - json2html,Python : json data not converted to html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39831894/

相关文章:

python - pip 不能使用自定义 SSL 证书?

javascript - 在 <video> 元素上播放多个音轨?

javascript - 在 PHP 的 where 子句中使用 span 文本

javascript - AngularJS 应用程序配置 "Uncaught object"错误 (ngRoute)

c# - 如何在 .NET Core MVC 项目中转换 appsettings.json?

Python:在列表中复制列表

Python - 使用正则表达式从文件中获取变量

python - 通过Python脚本查看Azure中虚拟机的故障和更新域

javascript - 创建一个没有未定义的json

json - 在 Flutter 中将 Json 数组转换为 List<Object>