如何将JSON数据转换为HTML表?

时间:2019-08-21 18:22:57

标签: python html json

我正在尝试将JSON数据(从S3存储桶接收到的)显示到类似HTML表格的结构中,但无法找到一种方法来实现。

import boto3
import json
import click
import requests

boto3.setup_default_session(profile_name='rli-dev', region_name='us-west-2')
s3 = boto3.resource('s3') 
content_object = s3.Object('bsdev-data-validation', 'awsnightlyendtoend_bsdev_2018-10-24T11:53:45Z/validate_adwactivityfact/job-details.json') 
file_content = content_object.get()['Body'].read().decode('utf-8-sig')
json_content = json.loads(file_content) 
print(json_content) 

我希望将“ json_content”中包含的JSON数据转换为类似HTML(table)的结构

1 个答案:

答案 0 :(得分:1)

使用json2html包:

  

$ pip安装json2html

import boto3
import json
import click
import requests
from json2html import *

boto3.setup_default_session(profile_name='rli-dev', region_name='us-west-2')
s3 = boto3.resource('s3') 
content_object = s3.Object('bsdev-data-validation', 'awsnightlyendtoend_bsdev_2018- 
10-24T11:53:45Z/validate_adwactivityfact/job-details.json') 
file_content = content_object.get()['Body'].read().decode('utf-8-sig')
json_content = json.loads(file_content)
print(json_content)

#Modify this to fit your need
input = {
    "name": "json2html",
    "description": "Converts JSON to HTML tabular representation"
}
test = json2html.convert(json = input)
print(test)

打印(测试)输出为:

<table border="1"><tr><th>name</th><td>json2html</td></tr><tr><th>description</th><td>Converts JSON to HTML tabular representation</td></tr></table>

您甚至可以创建JSON语句列表:

from json2html import *

input = [{
        "name": "John Doe",
        "description": "Generic Man",
        "some data": "['brown hair', '5.10, 'accountant']"
}, {
        "name": "Jane Doe",
        "description": "Generic woman",
        "some data": "['brown hair', '5.5, 'hair dresser']"
}]
test = json2html.convert(json = input)
print(test)

列表JSON的输出:

<table border="1"><thead><tr><th>name</th><th>description</th><th>some data</th></tr></thead><tbody><tr><td>John Doe</td><td>Generic
Man</td><td>[&#x27;brown hair&#x27;, &#x27;5.10, &#x27;accountant&#x27;]</td></tr><tr><td>Jane Doe</td><td>Generic woman</td><td>[&#x27;brown hair&#x27;, &#x27;5.5, &#x27;hair dresser&#x27;]</td></tr></tbody></table>