How to validate a json object in django

You can use django rest framework to validate request data as mentioned by @zaphod100.10 ,

here is the serializer you can use to validate-

from rest_framework import serializers

class PaymentSerializer(serializers.Serializer):
    amount = serializers.IntegerField(required=True, min_value=0, null=True)
    name = serializers.CharField(required=True, max_length=128)
    type = serializers.IntegerField(required=True, min_value=0)

class ValidateFormSerializer(serializers.Serializer):
    code = serializers.CharField(required=True, max_length=32)
    name = serializers.CharField(required=True, max_length=128)
    payments = serializers.ListField(child=PaymentSerializer)

You need like this to validate it in the view section -

 import ValidateFormSerializer

# add this snippet in your view section
 valid_ser = ValidateFormSerializer(data=request.data)
 if valid_ser.is_valid():
       post_data = valid_ser.validated_data
 else:
      print(valid_ser.errors)

Let me know, if it is enough to solve your problem.


There are a number of ways to validate json. I would list following:

  1. Marshmallow
  2. Schema Validation

Let me know if you need any help in using these