python - django.http.JsonResponse return json data in wrong format -


i want return queryset in json format, , use jsonresponse following:

def all_alert_history(request): ''' all alert history data '''     all_data_json = serializers.serialize('json', latestalert.objects.all())     return jsonresponse(all_data_json,safe=false) 

but browser shows this:

"[{\"fields\": {\"alert_name\": \"memory usage\", \"alert_value\": 83.7, \"alert_time\": \"2016-11-08t06:21:20.717z\", \"alert_level\": \"warning\", \"alert_rule\": \"warning: > 80%\"}, \"model\": \"alert_handler.latestalert\", \"pk\": \"xyz.test-java.ip-10-0-10-138.memory.percent\"}]" 

i replace jsonresponse httpresponse :

def all_alert_history(request): ''' all alert history data ''' all_data_json = serializers.serialize('json', latestalert.objects.all()) return httpresponse(all_data_json, content_type='application/json')  

and browser shows this:

[{"fields": {"alert_name": "memory usage", "alert_value": 83.7, "alert_time": "2016-11-08t06:21:20.717z", "alert_level": "warning", "alert_rule": "warning: > 80%"}, "model": "alert_handler.latestalert", "pk": "xyz.test-java.ip-10-0-10-138.memory.percent"}] 

so, why \ appears when use jsonresponse disappear when use httpresponse?

django version:1.8

jsonresponse takes python dictionary , returns json formatted string browser.

since you're providing jsonresponse json formatted string try escape necessary characters \.

example:

>>> django.http import jsonresponse >>> response = jsonresponse({'foo': 'bar'}) >>> response.content b'{"foo": "bar"}' 

in case jsonresponse warns doing when passing string, hence making safe = false parameter necessary:

>>> mydata = {"asd":"bdf"} >>> import json >>> myjson = json.dumps(mydata) >>> jsonresponse(myjson) traceback (most recent call last):   file "<stdin>", line 1, in <module>   file "/home/swozny/work2/local/lib/python2.7/site-packages/django/http/response.py", line 500, in __init__     raise typeerror('in order allow non-dict objects ' typeerror: in order allow non-dict objects serialized set safe parameter false 

with parameter set false observed behavior reproducible:

>>> jsonresponse(myjson,safe=false).content '"{\\"asd\\": \\"bdf\\"}"' 

bottom line if model little more complex basic data types ( integerfield,charfield,...) want serialization , stick httpresponse or use djangorestframework offers tools you.


Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - IE9 error '$'is not defined -