4

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.

1
  • 1
    JSON is a string format. Commented Aug 28, 2018 at 21:30

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.