Bird
0
0

What is wrong with this Django view code snippet for parsing JSON?

medium📝 Debug Q14 of 15
Django - REST Framework Basics
What is wrong with this Django view code snippet for parsing JSON?
def my_view(request):
    data = json.loads(request.POST)
    return JsonResponse({"status": "ok"})
Arequest.POST is empty for GET requests only
Brequest.POST is not a JSON string, so json.loads will fail
CThe function must return a string, not JsonResponse
DJsonResponse cannot be used without importing
Step-by-Step Solution
Solution:
  1. Step 1: Understand request.POST content

    request.POST is a QueryDict, not a JSON string, so passing it to json.loads() causes an error.
  2. Step 2: Correct JSON parsing method

    To parse JSON, use json.loads(request.body) instead, since request.body contains raw JSON bytes.
  3. Final Answer:

    request.POST is not a JSON string, so json.loads will fail -> Option B
  4. Quick Check:

    json.loads needs JSON string, not QueryDict [OK]
Quick Trick: Use request.body for JSON, not request.POST [OK]
Common Mistakes:
MISTAKES
  • Passing request.POST to json.loads
  • Assuming JsonResponse needs string return
  • Ignoring HTTP method differences

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes