Bird
0
0

How would you modify this Django view to handle invalid JSON in the request body gracefully?

hard📝 Application Q9 of 15
Django - REST Framework Basics
How would you modify this Django view to handle invalid JSON in the request body gracefully?
from django.http import JsonResponse
import json

def view(request):
    data = json.loads(request.body)
    return JsonResponse({'received': data})
AWrap json.loads in try-except block catching json.JSONDecodeError and return error JsonResponse
BUse request.POST instead of json.loads to avoid errors
CAdd content_type='application/json' to JsonResponse call
DUse json.dumps instead of json.loads
Step-by-Step Solution
Solution:
  1. Step 1: Identify error source

    json.loads can raise JSONDecodeError if request.body is invalid JSON.
  2. Step 2: Add try-except to catch error and respond gracefully

    Wrap parsing in try-except and return JsonResponse with error message on exception.
  3. Final Answer:

    Wrap json.loads in try-except catching JSONDecodeError -> Option A
  4. Quick Check:

    Use try-except to handle JSON parsing errors [OK]
Quick Trick: Catch JSONDecodeError to handle invalid JSON gracefully [OK]
Common Mistakes:
MISTAKES
  • Ignoring possible JSON parsing errors
  • Using request.POST to avoid JSON parsing
  • Misusing json.dumps instead of json.loads

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes