使用HTTPResponse返回美化字典

时间:2018-02-19 03:19:26

标签: python json django

我试图返回一个美化JSON的HTTPResponse对象。我知道indent的{​​{1}}参数仅在您打印时有效。并且打印将参数转换为字符串。因此,如果我在返回JSON之前仅json indentstr()参数是否有效?

def conversationview(request, convo_identification):
    data = InputInfo.objects.all()
    conversation_identification = convo_identification
    #conversation_id = {'conversation_id': []}
    header = {'conversation_id': '', 'messages': []}
    entry = {}
    output = {}

    for i in data:
        if str(i.conversation_id) == conversation_identification:
            header['conversation_id'] = i.conversation_id
            entry = {}
            entry['sender'] = i.name
            entry['message_body'] = i.message_body
            entry['date_created'] = str(i.created)
            header.get('messages').append(entry)
            #parsed = json.loads(header)
            convert_to_json = json.dumps(header, sort_keys=True, indent=4)
            output = str(convert_to_json)

    return HttpResponse(output) 

1 个答案:

答案 0 :(得分:2)

您在HttpResponse返回语句

中缺少content-type参数
return HttpResponse(convert_to_json,content-type='application/json')

或者如果你想在模板中传递它,请在<pre>标记中传递它,它会保留缩进