简体   繁体   中英

Getting a JSON request in a view (using Django)

I am trying to set up a view to received a JSON notification from an API. I'm trying to figure out how to get the JSON data, and I currently have this as a starting point to see that the request is being properly received:

def api_response(request):
    print request
    return HttpResponse('')

I know the JSON object is there because in the print request it shows:

META:{'CONTENT_LENGTH': '178',
[Fri Sep 09 16:42:27 2011] [error]  'CONTENT_TYPE': 'application/json',

However, both of the POST and GET QueryDicts are empty. How would I set up a view to receive the JSON object so I can process it? Thank you.

This is how I did it:

def api_response(request):
    try:
        data=json.loads(request.raw_post_data)
        label=data['label']
        url=data['url']
        print label, url
    except:
        print 'nope'
    return HttpResponse('')

On a function view, you can try this out.

dp = json.dumps(request.data)
contact = json.loads(dp)
print(contact['first_name'])

For Class-Based Views built Using Django-Rest-Framework, you can use built-in JSONParser to get JSON data in request.data

from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView

class MyOveridingView(APIView):
    parser_classes = [JSONParser]

class MyActualView(MyOveridingView):

    def post(self, request, *args, **kwargs):
        request_json = request.data
        return JsonResponse(data=request_json, status=200)

I'm going to post an answer to this since it is the first thing I found when I searched my question on google. I am using vanilla django version 3.2.9. I was struggling to retrieve data after making a post request with a json payload to a view. After searching for a while, I finally found the json in request.body .

Note: request.body is of type bytes , you'll have to decode it to utf-8, my_json_as_bytes.decode('utf-8')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM