html頁(yè)面展示Json樣式 by python

最近有個(gè)需求,從數(shù)據(jù)庫(kù)提取json,接口返回html,這里就涉及到用python生成個(gè)html,flask返回該html。
第一版做出來(lái)Json都在一起,看著很吃力,于是想用轉(zhuǎn)化成json展開的格式。

實(shí)現(xiàn)方式:

  1. python 用str 拼一個(gè)html
  2. 用html 頁(yè)面展示 json 樣式

用html 頁(yè)面展示 json 樣式

<html>
    </head>  </head>
    <body>
            <script>
                    var str = {"name":"菜鳥教程", "site":"http://www.runoob.com"}
                    str_pretty2 = JSON.stringify(str, null, 4) //使用四個(gè)空格縮進(jìn)
                    document.write("<pre>" + str_pretty2 + "</pre>" ); // pre 用于格式化輸出
            </script>
      </body>
</html>

自己建個(gè)html,打開就是這樣


image.png

下面是python實(shí)現(xiàn):

body = '<html><style>pre {outline: 1px solid #ccc; } p {background-color: #C0C0C0; }</style></head><body><h3>test</h3<script>'
body = body + 'var row =  {\"name\":\"菜鳥教程\", \"site\":\"http://www.runoob.com\"} ' + """ 
            """

body = body + 'row = JSON.stringify(row, null, 4)'  + """ 
            """

body = body + 'document.write(\"<pre>\" + row+ \"</pre>\"); ' + """
            """
body = body + '</script></body></html>'

遇到的坑1:

一開始沒(méi)有加""" ,html里的script生成都在一坨里面,大概就是這個(gè)樣子

var str = {"name":"菜鳥教程", "site":"http://www.runoob.com"} str_pretty2 = JSON.stringify(str, null, 4) document.write("<pre>" + str_pretty2 + "</pre>" );

所以要換行,加了"""就好了

            body = body + 'var row =  {\"name\":\"菜鳥教程\", \"site\":\"http://www.runoob.com\"} ' + """ 
            """

遇到的坑2:
之前運(yùn)行在python2.7上,最近部署了一臺(tái)python3,又蹦了。

業(yè)務(wù)邏輯:post 接口將json 存入數(shù)據(jù)庫(kù), get 接口把數(shù)據(jù)庫(kù)的json展示在頁(yè)面上,檢測(cè)下來(lái)數(shù)據(jù)庫(kù)里 Json boolean 字段全成Ture,F(xiàn)alse,因?yàn)閜ost插入數(shù)據(jù)庫(kù),json要轉(zhuǎn)化成str,寫進(jìn)sql 里面,這就涉及到python json 和str 互轉(zhuǎn)的問(wèn)題。理論上 Json里面是ture,dict 里面是大寫,不用json.dump() json,loads()基本就廢了。

原代碼:

@app.route('/set', methods=['POST'])
def post_Data():
    api_value = request.args.get('api', '')
    operateHandler = OperateManagement()
    return operateHandler.saveResult(api_value, request.json, request.remote_addr)

修改后

@app.route('/set', methods=['POST'])
def post_Data():
    api_value = request.args.get('api', '')
    operateHandler = OperateManagement()
    return operateHandler.saveResult(api_value, json.dumps(request.json), request.remote_addr)

然后就好了

記得import json

參考文檔:
使用 Python 自動(dòng)生成 HTML
https://blog.csdn.net/weixin_41697143/article/details/87607578

html頁(yè)面展示Json樣式
https://www.runoob.com/try/try.php?filename=tryjson_stringify

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容