使用django模板将json填充到html

时间:2012-02-11 07:33:00

标签: python django json django-templates

为了更好地调试我的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"
    }, 
}

2 个答案:

答案 0 :(得分:8)

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

例如:

json.dumps(spam_and_eggs, indent=4)

答案 1 :(得分: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>