Home > database >  Django Rest Framework parser does not accept string as valid JSON
Django Rest Framework parser does not accept string as valid JSON

Time:08-25

I'm sending some data to Django Rest Framework backend with Content-Type set as application/json. If I try to send any JSON that is shaped like a typical nested key-value object, everything works fine.

But if I want to send a simple string like test, I get a 400 Bad request due to malformed JSON : JSON parse error - Expecting value: line 1 column 1 (char 0).

But aren't strings valid JSON values according to RFC 8259 ?

I don't understand from the official DRF documentation if this is a normal feature for Django JSON Parser or if I'm doing something wrong somewhere ?

The class-based view that I'm using is ListCreateAPIView:

class ObjectList(ListCreateAPIView):
    """
    View dedicated to GET a list of instances or POST a new one
    """    
    serializer_class = MySerializer
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        # Filter objects based on user identity (token based)
        queryset = MyObject.objects.filter(user=self.request.user)
        return queryset
    
    def post(self, request, format=None):
        transect_data = request.data # Returns 400 Bad request

The piece of code that send data to the server (JS using Axios)

…
    return axios
      .post(API_URL   'create/', 
        "test",
        {
          headers: headers,
        }
      )
      .then(response => {
        return response.data;
      })
      .catch((error) => {
        console.log(error);
      });

CodePudding user response:

You can pass any JSON value [json.org], so that includes a string, but a string is put between double quotes ("…") and some characters should be escaped, so you send "test", not test.

test itself is not a valid JSON value. Indeed, you can check for example with the Online JSON valiator [jsonlint.com] if a JSON blob is valid JSON.

A string literal is, just like for example in Python and JavaScript thus put in an "envelope" of double quotes, and escapes certain characters such that if the string itself contains a double quote, that character is escaped properly.

  • Related