Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON validate extra parameter using schema

I want to validate a json input through json schema. The positive case works for intended objects and properties. But I want to validate against extra objects, parameters which are not mentioned in the schema.

Basically fail the validation if garbage data detected in the json

like image 984
Gaurav Avatar asked Jan 23 '13 19:01

Gaurav


People also ask

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.

How do you validate a JSON file against a schema?

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.

What is additional properties in JSON Schema?

Additional Properties The value of the additionalProperties keyword is a schema that will be used to validate any properties in the instance that are not matched by properties or patternProperties . Setting the additionalProperties schema to false means no additional properties will be allowed.

What does JSON Schema validator do?

JSON Schema validation asserts constraints on the structure of instance data. An instance location that satisfies all asserted constraints is then annotated with any keywords that contain non-assertion information, such as descriptive metadata and usage hints.


1 Answers

If you want to only have a certain set of properties in JSON objects and refuse others:

  • ensure the properties you want have a matching schema in either properties and patternProperties,
  • define additionalProperties to false:

    {
        "type": "object",
        "properties": { "p": {}, "q": {} },
        "additionalProperties": false
    }
    

will only allow for properties p and q to exist in object instances.

like image 162
fge Avatar answered Oct 01 '22 17:10

fge