简体   繁体   English

Django 编辑 JsonResponse

[英]Django Editing JsonResponse

How I can add "points = " to this JsonResponse in Django?如何在 Django 中向这个 JsonResponse 添加“points =”?

My code look like this:我的代码如下所示:

return JsonResponse(data=points, safe=False, json_dumps_params={'indent': 1})

Result:结果:

[ { "x": 0, "y": 1 }, { "x": 0.315397047887207, "y": 0.694608645422627 } ] [{“x”:0,“y”:1},{“x”:0.315397047887207,“y”:0.694608645422627}]

what I want to do:我想做的事:

points=[ { "x": 0, "y": 1 }, { "x": 0.315397047887207, "y": 0.694608645422627 } ]点=[{“x”:0,“y”:1},{“x”:0.315397047887207,“y”:0.694608645422627}]

Look like you don't need JSON response.看起来您不需要 JSON 响应。 you need to pass a string in JSON.您需要在 JSON 中传递一个字符串。

for output like this: points=[ { "x": 0, "y": 1 }, { "x": 0.315397047887207, "y": 0.694608645422627 } ]对于 output 像这样:points=[ { "x": 0, "y": 1 }, { "x": 0.315397047887207, "y": 0.694608645422627 } ]

points_dict = {
    // value for points_key you can do some string concatenation for dynamic value
    'points_key': 'points=[ { "x": 0, "y": 1 }, { "x": 0.315397047887207, "y": 0.694608645422627 } ]'
}
return JsonResponse(data=points_dict, safe=False, json_dumps_params={'indent': 1})

As was mentioned before me, the response you want is not a JSON format.正如我之前提到的,您想要的响应不是 JSON 格式。 As was suggested by a different answer, you can convert it into a string and send it like that:正如另一个答案所建议的那样,您可以将其转换为字符串并像这样发送:

pointsstr = f'points=[{points_dict}]'
return HttpResponse(pointsstr)

If you want to still use a JSON format then I suggest doing the following:如果您仍想使用 JSON 格式,那么我建议您执行以下操作:

return JsonResponse(data={'points': points}, safe=False, json_dumps_params={'indent': 1})

This way your response would be: {"points": [{ "x": 0, "y": 1 }, { "x": 0.315397047887207, "y": 0.694608645422627 }]}这样,您的响应将是: {"points": [{ "x": 0, "y": 1 }, { "x": 0.315397047887207, "y": 0.694608645422627 }]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM