简体   繁体   中英

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

I have a current API set up in flask-SQLAlchemy that returns an output in JSON format that I'm having trouble putting into a presentable tabular or HTML format. I'd like it to be presented in a more tabular form rather than the JSON form on my web page.

I've tried using the 'json2html' package to convert the json_data but it's only outputting 'Content-Type application/json' in a incorrect format. The jsonify function returns a RESPONSE in JSON form. Any simple suggestions or fixes to get the data presented in a tabular form would help!

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"
    ]
  ]
}

I expected a table-like output with 7 column fields and X number of rows based on what is generated from my GET methods. I think the issue is related to the format that the JSON file is getting created in but I haven't been able to debug it.

Your data_all is a list of lists. If you pass a list of dicts to json2html it will format it as an HTML table for you.

For example:

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

Then you can pass this list to json2html :

html_data = json2html.convert(json=data_all)

The resulting HTML will be in the following format:

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

You can pass your json data to the json2html module and then pass that variable to the html template.

In the flask python file have a route configured -

@app.route('/json_html')

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

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

and the json_template.html can have the following structure

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

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

   </body>
</html> 

| safe ensures that the html code will not be escaped and be parsed properly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM