簡體   English   中英

在 Python - Flask 中將 JSON 數據輸出轉換為 HTML-TABLE 格式?

[英]Converting a JSON data output to a HTML-TABLE format in Python - Flask?

我在flask-SQLAlchemy 中設置了一個當前的API,它返回JSON 格式的輸出,我無法將其放入可呈現的表格或HTML 格式。 我希望它在我的網頁上以更表格的形式呈現,而不是 JSON 形式。

我嘗試使用 'json2html' 包來轉換 json_data 但它只以不正確的格式輸出 'Content-Type application/json'。 jsonify 函數以 JSON 格式返回 RESPONSE。 任何以表格形式顯示數據的簡單建議或修復都會有所幫助!

from flask import Flask,jsonify, request, Response, render_template,redirect, url_for
import configparser, pymysql, json, requests
from json2html import *
from flask_sqlalchemy import SQLAlchemy

# API method to get a hike recommendation. This takes a URL containing several arguments related to hike preferences
@app.route('/findhike_result', methods=['GET'])
def findBestHike():
    park = request.args.get('park')
    level = request.args.get('level')
    min = request.args.get('min')
    max = request.args.get('max')
    bath= request.args.get('bath')
    dog= request.args.get('dog')
    feat1= request.args.get('feat1')
    feat2= request.args.get('feat2')
    feat3= request.args.get('feat3')
    feat4= request.args.get('feat4')
    feat5= request.args.get('feat5')
    proc_call = "call find_the_best_hike('" + park + "','" + level + "','" + min + "','" + max + "','" + bath + "','" \
                + dog + "','" + feat1 + "','" + feat2 + "','" + feat3 + "','" + feat4 + "','" + feat5 + "')"
    print(proc_call)
    result = mysql.engine.execute(proc_call)
    data_all = []
    for item in result:
        data_all.append([item['trail name'], str(item['distance in miles']), item['description'],
                         str(item['average user rating']), item['features'], item['messages'], str(item['score'])])

    json_data = jsonify(trails=data_all),{'Content-Type':'application/json'}

    return json2html.convert(json=json_data)


**Sample JSON OUTPUT**

{
  "trails": [
    [
      "Upper Yosemite Falls", 
      "7.20", 
      "Upper Yosemite Falls Trail is a 7.2 mile heavily trafficked out and back trail located near Yosemite Valley, California that features a waterfall and is only recommended for very experienced adventurers. The trail offers a number of activity options and is accessible year-round.", 
      "2.53", 
      "Upper Yosemite Falls has Waterfall , Climbing , Rocky , Forest , Scenic Views as features.", 
      "Upper Yosemite Falls goes above Alpine Zone. Please use caution.", 
      "5.00"
    ], 
    [
      "Vernal and Nevada Falls via the Mist Trail", 
      "6.40", 
      "Vernal and Nevada Falls via the Mist Trail is a 6.4 mile heavily trafficked loop trail located near Yosemite Valley, California that features a waterfall and is rated as difficult. The trail is primarily used for hiking, walking, nature trips, and bird watching and is best used from April until October.", 
      "3.18", 
      "Vernal and Nevada Falls via the Mist Trail has Waterfall , Rocky , Forest , Scenic Views as features.", 
      "Have fun hiking Vernal and Nevada Falls via the Mist Trail!", 
      "3.80"
    ], 
    [
      "Half Dome", 
      "14.80", 
      "Half Dome Trail is a 14.8 mile heavily trafficked out and back trail located near Yosemite Valley, California that features a waterfall and is only recommended for very experienced adventurers. The trail is primarily used for hiking, rock climbing, and nature trips and is best used from April until October.", 
      "3.07", 
      "Half Dome has Waterfall , Rocky , Forest , Scenic Views as features.", 
      "Half Dome requires a permit. Please consult with Park Rangers before attempting this trail. Half Dome is a long hike. Consider doing this trail over multiple days. Half Dome goes above Alpine Zone. Please use caution.", 
      "3.80"
    ], 
    [
      "Four Mile Trail", 
      "7.50", 
      "Four Mile Trail is a 7.5 mile heavily trafficked out and back trail located near Yosemite Valley, California that features a waterfall and is only recommended for very experienced adventurers. The trail offers a number of activity options and is best used from April until November.", 
      "3.00", 
      "Four Mile Trail has Waterfall , Forest , Scenic Views as features.", 
      "Four Mile Trail goes above Alpine Zone. Please use caution.", 
      "2.80"
    ], 
    [
      "North Dome", 
      "13.70", 
      "Yosemite Falls Trail to North Dome is a 13.7 mile out and back trail located near Yosemite Valley, California that offers the chance to see wildlife and is rated as difficult. The trail is primarily used for hiking, nature trips, and bird watching.", 
      "2.45", 
      "North Dome has Waterfall , Forest , Scenic Views as features.", 
      "North Dome is a long hike. Consider doing this trail over multiple days. North Dome goes above Alpine Zone. Please use caution.", 
      "2.80"
    ]
  ]
}

根據我的 GET 方法生成的內容,我希望有一個類似表格的輸出,它有 7 個列字段和 X 行。 我認為這個問題與創建 JSON 文件的格式有關,但我無法調試它。

您的data_all是一個列表列表。 如果您將字典列表傳遞給json2html ,它將為您將其格式化為 HTML 表格。

例如:

data_all = []
for item in result:
    data_all.append({
        "Name": item["trail name"],
        "Description": item["description"]
    })

然后您可以將此列表傳遞給json2html

html_data = json2html.convert(json=data_all)

生成的 HTML 將采用以下格式:

<table border="1">
<thead>
  <tr><th>Name</th><th>Description</th></tr>
</thead>
<tbody>
  <tr>
    <td>Upper Yosemite Falls</td>
    <td>Upper Yosemite Falls Trail ...</td>
  </tr>
  <tr>
    <td>Vernal and Nevada Falls via the Mist Trail</td>
    <td>Vernal and Nevada Falls via the Mist Trail is a 6.4 mile ...</td>
  </tr>
</tbody>
</table>

您可以將 json 數據傳遞給 json2html 模塊,然后將該變量傳遞給 html 模板。

在flask python文件中配置了一個路由 -

@app.route('/json_html')

def json_html():
    
    table_data = (json2html.convert(json = json_data))

    return render_template("json_template.html", table_data=table_data)

並且 json_template.html 可以具有以下結構

<!doctype html>
<html>
<head>  
</head>
   <body>

  <div>
      {{json_data | safe}}
  </div>

   </body>
</html> 

| safe 確保 html 代碼不會被轉義並被正確解析

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM