我试图返回一个美化JSON的HTTPResponse
对象。我知道indent
的{{1}}参数仅在您打印时有效。并且打印将参数转换为字符串。因此,如果我在返回JSON之前仅json
indent
,str()
参数是否有效?
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)
答案 0 :(得分:2)
您在HttpResponse
返回语句
return HttpResponse(convert_to_json,content-type='application/json')
或者如果你想在模板中传递它,请在<pre>
标记中传递它,它会保留缩进