Skip to content Skip to sidebar Skip to footer

Json Parsing Django Rest Framework

I want to parse incoming POST data in django views.py file POST data: { 'number' : '17386372', 'data' : ['banana','apple','grapes' ] } Here is how I tried to read above incomin

Solution 1:

The Django json parser does this already for you:

from rest_framework import parsers

classFruits(APIView):
    parser_classes = (parsers.JSONParser,)

    defpost(self, request, format=None):
        number = request.data['number']
        fruits = request.data['data']

If the Content-Type of your http request is already set properly to application/json you do not even need to specify the parser.

Solution 2:

request.data and request.body are the two mechanisms, which reads the raw http request and construct data in a format, that is suitable to be used in python environment. Here the problem is that you are using both of them simultaneously. Thus, the inputstream of http connection is already read, by request.data call. Now request.body also tries to access the same stream, which doesn't contain now any data. Thus, it's throwing an error.

For you, I think following code will work :

fruits_data = json.loads(request.body)
number = fruits_data["number"]

Post a Comment for "Json Parsing Django Rest Framework"