如何在Flask网页中展示LayoutLM OCR返回的JSON字段值?
把LayoutLM OCR结果JSON展示到Flask HTML页面的方案
1. 调整Flask路由,传递OCR结果到模板
修改app.py的上传处理逻辑,把OCR返回的字典数据传给HTML模板:
from flask import Flask, render_template, request import main import json # 如果main返回的是JSON字符串,需要引入这个 app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def upload_and_ocr(): ocr_data = None if request.method == 'POST': uploaded_file = request.files.get('file') if uploaded_file and uploaded_file.filename != '': # 调用main.py的文档处理函数 raw_result = main.process_document(uploaded_file) # 若main返回的是JSON字符串,转成Python字典 # ocr_data = json.loads(raw_result) # 若直接返回字典,直接赋值即可 ocr_data = raw_result # 将OCR结果传入模板 return render_template('index.html', ocr_results=ocr_data) if __name__ == '__main__': app.run(debug=True)
2. 修改HTML模板,用Jinja2渲染结果
在index.html里添加结果展示区域,用Jinja2模板语法遍历键值对:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>文档OCR识别</title> <style> .result-table { margin-top: 20px; border-collapse: collapse; } .result-table th, .result-table td { border: 1px solid #ddd; padding: 8px; text-align: left; } .result-table th { background-color: #f2f2f2; } </style> </head> <body> <!-- 文件上传表单 --> <form method="POST" enctype="multipart/form-data"> <input type="file" name="file" accept=".jpg,.png,.pdf" required> <button type="submit">上传识别</button> </form> <!-- OCR结果展示区域 --> {% if ocr_results %} <h3>识别结果</h3> <table class="result-table"> <tr> <th>字段名</th> <th>对应值</th> </tr> {% for field, value in ocr_results.items() %} <tr> <td>{{ field }}</td> <td>{{ value }}</td> </tr> {% endfor %} </table> {% endif %} </body> </html>
关键注意点
- 确保
main.py的处理函数返回Python字典,如果返回的是JSON字符串,必须先用json.loads()转成字典再传给模板。 - 如果OCR结果包含嵌套结构(比如子字典、列表),需要调整Jinja2的遍历逻辑,比如添加嵌套的
{% for %}循环来处理层级数据。
内容的提问来源于stack exchange,提问作者Akshit
相关产品推荐
相关产品推荐

