Naroju Naroju - 1 year ago 291
Python Question

Json parsing django rest framework

I want to parse incoming

data in django file

POST data:

"number" : "17386372",
"data" : ["banana","apple","grapes" ]

Here is how I tried to read above incoming data with

class Fruits(APIView):

def post(self, request, format=None):

if request.method == "POST":

number ='number')
fruits_data = json.loads(request.body)

if number not in [None, '', ' ']:

response = {"return": "OK","data":fruits_data['data']}
return Response(response)
return Response({"return": "NOT OK"})
return Response({"return": "NOT OK"})

return Response({"return": "NOT OK"})


You cannot access body after reading from request's data stream

Answer Source 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 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"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download