首页 > 解决方案 > How to format json file view on html

问题描述

current json view on html page

{"result": [{"id": "103300640", "sms_phone": "730276061", "corrected to": 
"27730276061"}, {"id": "103277733", "sms_phone": "716125197", "corrected 
 to": "27716125197"}]}

what I want it to be formatted display like

{  
   "result":[  
      {  
         "id":"103300640",
         "sms_phone":"730276061",
         "corrected to":"27730276061"
      },
      {  
         "id":"103277733",
         "sms_phone":"716125197",
         "corrected to":"27716125197"
      }]
}

JS code:

@app.route('/<path:req_path>')
def dir_listing(req_path):
   abs_path = os.path.join(UPLOAD_FOLDER, req_path)
   # Check if path is a file and serve
   if os.path.isfile(abs_path):
      return send_file(abs_path, mimetype="application/json")    
return render_template('/index.html')

HTML code:

<ul>
    {% for file in file_list %}
    <li><a href="{{ file }}" id="list">{{ file }}</a></li>
    {% endfor %}
</ul>

标签: htmljson

解决方案


你可以试试这个:

使用<pre>标签在HTML页面中显示代码本身并使用JSON.stringify().

var data = {"result": [{"id": "103300640", "sms_phone": "730276061", "corrected to": "27730276061"}, {"id": "103277733", "sms_phone": "716125197", "corrected  to": "27716125197"}]}


document.getElementById("beautified").innerHTML = JSON.stringify(data, undefined, 2);
<pre id="beautified"></pre>

JSON.stringify()方法将 JavaScript 对象或值转换为 JSON 字符串,如果指定了替换函数,则可选地替换值,或者如果指定了替换器数组,则可选地仅包括指定的属性。


推荐阅读