Junior
What is a JSON schema?
sobes.tech AI
Answer from AI
JSON Schema is a lexical standard based on JSON for describing the structure and constraints of data in JSON format. It allows validation, description, and documentation of JSON data.
Main goals:
- Validation: Checking if a JSON instance conforms to a specified structure.
- Documentation: Describing the JSON data format.
- Interaction: Exchanging metadata between systems.
Key components of JSON Schema:
- Data types:
string,number,integer,boolean,object,array,null. - Keywords for constraints:
type: Expected data type.properties: Description of object properties. Each property has its own subschema.required: List of mandatory properties for the object.items: Description of array elements.minLength/maxLength: Length constraints for strings.minimum/maximum: Number constraints.pattern: Regular expression for strings.enum: List of allowed values.allOf/anyOf/oneOf/not: Logical combinations of schemas.
- Keywords for metadata:
title: Short name of the schema.description: Detailed description of the schema.default: Default value.
Example of a JSON Schema:
{
"type": "object",
"properties": {
"id": {
"type": "integer",
"description": "Unique user identifier"
},
"username": {
"type": "string",
"minLength": 3
},
"isActive": {
"type": "boolean",
"default": true
}
},
"required": [
"id",
"username"
]
}
Example of JSON data valid according to this schema:
{
"id": 123,
"username": "testuser",
"isActive": false
}
Example of JSON data invalid according to this schema:
{
"id": "abc" // Invalid type
// Missing required field "username"
}
Using JSON Schema in QA Automation:
- API response validation: Checking if JSON responses match the specified format.
- Request validation: Checking incoming JSON data before processing.
- Test data generation: Using the schema to create valid (or invalid) test examples.
- Documentation: Creating automatically maintained API documentation.
There are libraries for working with JSON Schemas in various programming languages (e.g., jsonschema for Python, json-schema-validator for Java).