Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a json object in django

I'm submitting a JSON to a django view with AJAX. The JSON looks like the following:

{
   "code":"9910203040", // required
   "name":"Abc", // required
   "payments":[
      {
         "amount":300, // required
         "name":"efg", // required,
         "type": 2 // can be empty
      },
      {
         "amount":100,
         "name":"pqr",
         "type": 3
      }
   ]
}

The payments list can be of any size. How can I validate this in Django? Is it possible to use Django Forms to validate this? If it was Spring, I would create Request classes and use annotations on fields but can't figure out how to do this in Django.

like image 703
Nayan Avatar asked May 20 '17 11:05

Nayan


People also ask

How do I validate a JSON file?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.

Can we validate JSON with schema?

JSON Schema is a powerful tool. It enables you to validate your JSON structure and make sure it meets the required API. You can create a schema as complex and nested as you need, all you need are the requirements. You can add it to your code as an additional test or in run-time.

What is a JSON validator?

JSON Validator verifies that your JavaScript Object Notation adheres to the JSON specification: www.json.org. JSON Validator also formats or humanizes your JSON to render it readable following common linting practices such as multi-line and indentation.


1 Answers

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.

like image 193
tom Avatar answered Sep 22 '22 23:09

tom