Why does JSON returned from the django rest framework have forward slashes in the response?

后端 未结 1 1622
盖世英雄少女心
盖世英雄少女心 2021-01-02 03:54

My response code

from rest_framework.response import Response
import json
responseData = { \'success\' : True }
return Response(json.dumps(responseData))


        
相关标签:
1条回答
  • 2021-01-02 04:33

    You are rendering the data to JSON twice. Remove your json.dumps() call.

    From the Django REST documentation:

    Unlike regular HttpResponse objects, you do not instantiate Response objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives.

    The Django REST framework then takes care of producing JSON for you. Since you gave it a string, that string was JSON encoded again:

    >>> import json
    >>> responseData = { 'success' : True }
    >>> print json.dumps(responseData)
    {"success": true}
    >>> print json.dumps(json.dumps(responseData))
    "{\"success\": true}"
    

    The framework uses Content Negotiation to determine what serialisation format to use; that way your API clients can also request that the data is encoded as YAML or XML, for example.

    Also see the Responses documentation:

    REST framework supports HTTP content negotiation by providing a Response class which allows you to return content that can be rendered into multiple content types, depending on the client request.

    0 讨论(0)
提交回复
热议问题