【问题标题】:populate json to html with django template使用 django 模板将 json 填充到 html
【发布时间】:2012-03-03 13:29:09
【问题描述】:

为了更好地调试我的 api,我想创建一个调试页面,逐行显示响应 json obj 的所有详细信息。我认为可以通过代码或 django 模板来完成。最简单的方法是什么?

https://developers.facebook.com/tools/explorer/?method=GET 例如,facebook explorer 确实会像这样列出响应 json obj 的详细信息。

{
  "id": "xxx", 
  "name": "xxx", 
  "first_name": "xxx", 
  "last_name": "xxx", 
  "link": "xxx", 
  "username": "xxx", 
  "hometown": {
    "id": "xxx", 
    "name": "xxx"
  }, 
  "location": {
    "id": "xxx", 
    "name": "xxx"
  }, 
  "bio": "Drink Coffee in Whitehorse", 

  "work": [
    {
      "employer": {
        "id": "xxx", 
        "name": "xxx"
      }, 
      "location": {
        "id": "xxx", 
        "name": "xxx"
      }, 
      "position": {
        "id": "xxx", 
        "name": "xxx"
      }, 
      "start_date": "2009-01", 
      "end_date": "0000-00"
    }, 
}

【问题讨论】:

    标签: python django json django-templates


    【解决方案1】:

    您只需调用json.dumps() 并使用indent 关键字参数等于缩进生成的JSON 的空格数以进行漂亮的打印。

    例如:

    json.dumps(spam_and_eggs, indent=4)
    

    【讨论】:

      【解决方案2】:

      我可以建议在您的 HTML 中使用 <pre></pre> 以使您的 json 看起来更漂亮。

      import json
      from django.contrib.admin.views.decorators import staff_member_required
      from django.shortcuts import render
      from .models import Scan
      
          @staff_member_required
          def info(request):
              my_info = Scan.scan()
              return render(request, 'info.html', {'info': json.dumps(my_info, indent=4)})
      

      HTML:

      <!DOCTYPE html>
          <html lang="en">
          <head>
              <meta charset="UTF-8">
              <title>Title</title>
          </head>
          <body>
              <pre>{{ info|safe }}</pre>
          </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 2019-01-07
        • 2016-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-02
        • 2022-01-17
        • 1970-01-01
        相关资源
        最近更新 更多