Done!

Can you provide an example of reusing schemas with $ref in JSON Schema?

Technology
Computer Science
Engineering

Progress

6 steps completed!11.62 sec

Answer

Certainly! In JSON Schema, you can reuse schemas by referencing them using the $ref keyword. This is particularly useful for defining common components like objects or arrays that appear multiple times in your JSON data. Below is an example that demonstrates how to reuse schemas with $ref.

Example JSON Schema:

{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "user": { "$ref": "#/definitions/user" }, "items": { "type": "array", "items": { "$ref": "#/definitions/item" } } }, "definitions": { "user": { "type": "object", "properties": { "id": { "type": "integer" }, "name": { "type": "string" }, "email": { "type": "string", "format": "email" } }, "required": ["id", "name", "email"] }, "item": { "type": "object", "properties": { "productId": { "type": "integer" }, "quantity": { "type": "integer" } }, "required": ["productId", "quantity"] } }, "required": ["user", "items"] }

Explanation:

  1. Root Object: The root schema is an object that has two properties: user and items.

  2. Reusing User Schema: The user property uses $ref to reference the user definition under definitions. This schema defines a user object with an id, name, and email.

  3. Reusing Item Schema: The items property is an array of items where each item schema is referenced using $ref to the item definition. This schema outlines the structure of each item in the array, including productId and quantity.

  4. Required Properties: Both the user and each item must contain certain required properties defined in their respective schemas.

This approach enhances maintainability and reduces redundancy by enabling you to define the structure for common components in one place and reference them throughout your schema.