Django JSONResponse is returning a string and not JSON

Viewed 2044

I am using a Django view to return a JSON object. However when I use the method below, I get a string representation of the dictionary and not a JSON object.

def api_dataset_index(request):
    upload_file = request.FILES.get('file')
    if upload_file:
        config_str = upload_file.read().decode("utf-8")
        d = Dataset.from_yaml(config_str)
        return JsonResponse(model_to_dict(d))

Response - "{\"id\": 31, \"name\": \"effort\", \"description\": \"Expressions of customer effort or ease.\", \"multilabeled\": false}"

Am I doing something wrong here? or is JSONResponse supposed to return a string?

Edit -

A string is a valid json representation. However, the content-type for the django.http method "JsonResponse" is being sent as a string rather than as an object. If the structure being passed to the JsonResponse() method is a list, then the encoding is done properly, that is, the client receives it as a json object and not just as a string.

Edit2

Turns out the issue I encountered was on client side code.

2 Answers

That is a string representation of a JSON object, and that should be what is returned. On the client side ou can create a JSON object from it just b paring it with something like:

var jsonObj = JSON.parse(response)

See doumentation here: W3Schools JSON.parse() or here MDN JSON.parse()

Try this:

import json    

def getObjects():
   objects = ...
   return JsonResponse(json.loads(objects))

You should already be sure the method is returned a json not a String

Related