【问题标题】:How to format json file view on html如何在html上格式化json文件视图
【发布时间】:2019-05-19 22:07:41
【问题描述】:

html页面上的当前json视图

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

我希望它被格式化显示为

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

JS代码:

@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 代码:

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

【问题讨论】:

  • 所以你只想格式化json?
  • 我相信其他类似问题已经回答了这个问题。你可能想看看这个one
  • 这对我没有帮助。我在 html 页面上列出了 json 文件,用户点击它应该打开美化的 json 格式。

标签: html json


【解决方案1】:

你可以使用JSON.stringify

参见示例:https://codepen.io/adrianparr/pen/VeyeVP

【讨论】:

  • 我的是 json 文件。如何在此代码中使用该
     标记 - 
      {% for file in file_list %}
    • {{ file }}
    • {% endfor %}
  • 请在 stackBlitz 中提供您的代码以启用编辑
【解决方案2】:

你可以试试这个:

使用&lt;pre&gt;标签在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);
&lt;pre id="beautified"&gt;&lt;/pre&gt;

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

【讨论】:

  • json 在文件中,代码是
  • 我的意思是如何将“pre”标签用于类似于上面给出的代码示例的 json 文件。
  • 你可以在 HTML 而不是 JSON 文件中使用它。
  • 是的 html 文件(根据示例)只有我问。在上面的这个问题描述中,我提到了 HTML 代码。您能修改一下并粘贴到这里吗?
  • 不错,简单的答案。
【解决方案3】:

你必须使用 JS 来实现这一点。 请看下面的代码。 使用&lt;pre&gt; 标签来实现这一点。

<html>
<head>
</head>
<body onload="myFunction()">
<script>
function myFunction() {
var data = {
    "data": {
        "x": "1",
        "y": "1",
        "url": "http://test.com"
    },
    "event": "start",
    "show": 1,
    "id": 50
}


document.getElementById("json").innerHTML = JSON.stringify(data, undefined, 2);
}

</script>
<pre id="json"></pre>
</body>
<html>

【讨论】:

    猜你喜欢
    • 2015-03-01
    • 1970-01-01
    • 2013-06-16
    • 2011-06-22
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    相关资源
    最近更新 更多