Reputation: 1530
I'm returning data as a JSON via Python/Django.
I used the below code:
jsonObject = serializers.serialize('json', object, fields=('value', 'record_time'))
return HttpResponse(json.dumps(jsonObject), mimetype="application/json")
The problem is I'm getting the response as below:
"[{\"pk\": null, \"model\": \"model.table\", \"fields\": {\"record_time\": \"2009-11-18T22:45:44Z\", \"value\": 0.6533125480476399}}, {\"pk\": null, \"model\": \"model.table\", \"fields\": {\"record_time\": \"2009-11-19T15:02:15Z\", \"value\": 0.4386133754377899}}]"
where as I should be getting it in below format:
"[
{
"pk": null,
"model": "model.table",
"fields":
{
"record_time": "2009-11-18T22:45:44Z",
"value": 0.6533125480476399
}
},
{
"pk": null,
"model": "model.table",
"fields":
{
"record_time": "2009-11-19T15:02:15Z",
"value": 0.4386133754377899
}
}
]"
Where am I going wrong here?
Upvotes: 0
Views: 2939
Reputation: 15692
You are serializing the object into jsonObject
, but you return the original object
. Just fix that and everything should work as expected.
Update:
Just change your code like this:
jsonObject = serializers.serialize('json', object, fields=('value', 'record_time'))
return HttpResponse(jsonObject, mimetype="application/json")
The change is the jsonObject
in the second line.
Upvotes: 1
Reputation: 599490
Where you're going wrong is confusing the printed representation of a JSON string with the actual string itself. Those slashes are just the console showing that the double-quotes inside the string are not ending the string, but are part of it. In other words, your JSON is just fine.
Upvotes: 0