简体   繁体   中英

Django Editing JsonResponse

How I can add "points = " to this JsonResponse in Django?

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 } ]

what I want to do:

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

Look like you don't need JSON response. you need to pass a string in JSON.

for output like this: 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. 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:

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 }]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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