[英]Return JSON from Django template
我已經查看了該問題的一些現有答案,但無法解決我的問題。
我的觀點之一是python字典。 我使用json.dumps()將其轉換為json,然后將其發送到模板。
如果所有JSON值都沒有空格,則模板會正確返回JSON。 但是,如果鍵的值由空格分隔,則模板返回的JSON字符串將在空格之后被截斷。
Android SDK讀取返回的JSON字符串,並且如果任何鍵具有空格分隔的值,這就是我所知道的返回的JSON字符串被截斷的方式。
views.py:
@api_view(['POST'])
@permission_classes((AllowAny, ))
def temp(request):
if request.method == 'POST':
response_dict = {}
response_dict['KEY1'] = 'hello'
response_dict['KEY2'] = 'hello world'
param_dict = json.dumps(response_dict, separators=(',', ':'))
return render(request, 'validate.html', {'params_dict': param_dict})
validate.html
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-I">
<title>HELLO</title>
<script type="text/javascript">
function response(){
return document.getElementById('response').value;
}
</script>
</head>
Redirect back to the app<br>
<form name="frm" method="post">
<input type="hidden" id="response" name="responseField" value={{ params_dict }}>
</form>
如上圖所示,如果KEY2的值“ hello world”不帶空格,即“ helloworld”,則模板正確返回JSON字符串ss,否則將在“ hello”之后截斷
您應該將值包裝在模板中的引號中:
<input type="hidden" id="response" name="responseField" value="{{ params_dict }}">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.