【问题标题】:Django Editing JsonResponseDjango 编辑 JsonResponse
【发布时间】:2021-06-12 01:49:01
【问题描述】:

如何在 Django 中向这个 JsonResponse 添加“points =”?

我的代码如下所示:

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

结果:

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

我想做什么:

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

【问题讨论】:

  • 您想要的返回不是有效的 JSON。你真的需要 JSON 响应吗?

标签: json python-3.x django jsonresponse


【解决方案1】:

正如我之前提到的,您想要的响应不是 JSON 格式。 正如另一个答案所建议的那样,您可以将其转换为字符串并像这样发送:

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

如果您仍想使用 JSON 格式,那么我建议您执行以下操作:

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

这样您的响应将是: {"points": [{ "x": 0, "y": 1 }, { "x": 0.315397047887207, "y": 0.694608645422627 }]}

【讨论】:

    【解决方案2】:

    看起来您不需要 JSON 响应。您需要在 JSON 中传递一个字符串。

    对于这样的输出: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})
    

    【讨论】:

    • 为什么要返回带有 JsonResponse 而不是 HttpResponse 的字符串?
    猜你喜欢
    • 2021-03-22
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 2020-10-17
    • 2017-12-24
    • 2016-04-20
    • 2019-11-21
    相关资源
    最近更新 更多