如何在django中为结果对象整齐地显示这个嵌套的json对象?

时间:2017-12-05 12:44:30

标签: python json django

这是我的view.py:

def dublinbus(request):

    template = loader.get_template('park_at_dcu/dublinbus.html')
    busstop = request.GET.get('busstop', '')
    busstop_url = 'https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid='+busstop+'&format=json'
    bus_time_info = requests.get(busstop_url)
    return HttpResponse(template.render(bus_time_info.json(), request))

这是JSON数据:

{"errorcode": "0",
 "errormessage": "",
 "numberofresults": 1,
 "stopid": "1644",
 "timestamp": "05\/12\/2017 12:22:09",
 "results":[{"arrivaldatetime": "05\/12\/2017 13:11:49",
             "duetime": "49",
             "departuredatetime": "05\/12\/2017 13:11:49",
             "departureduetime": "49",
             "scheduledarrivaldatetime": "05\/12\/2017 13:12:00",
             "scheduleddeparturedatetime": "05\/12\/2017 13:12:00",
             "destination": "Clontarf Road ",
             "destinationlocalized": " ",
             "origin": "DCU",
             "originlocalized": "DCU",
             "direction": "Inbound",
             "operator": "bac",
             "additionalinformation": "",
             "lowfloorstatus": "no",
             "route": "104",
             "sourcetimestamp": "05\/12\/2017 12:15:24",
             "monitored": "true"}]
}

1 个答案:

答案 0 :(得分:0)

你可以使用json.dumps。

json.dumps(parsed, indent=4, sort_keys=True)



def dublinbus(request):

    template = loader.get_template('park_at_dcu/dublinbus.html')
    busstop = request.GET.get('busstop', '')
    busstop_url = 'https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid='+busstop+'&format=json'
    bus_time_info = requests.get(busstop_url)
    pretty_bus_info = json.dumps(bus_time_info.json(), indent=4, sort_keys=True)
    return HttpResponse(template.render(pretty_bus_info, request))