Skip to content

Instantly share code, notes, and snippets.

@razhangwei
Last active November 7, 2024 23:44
Show Gist options
  • Save razhangwei/2660466fabb9df652f62a3d2d27139f3 to your computer and use it in GitHub Desktop.
Save razhangwei/2660466fabb9df652f62a3d2d27139f3 to your computer and use it in GitHub Desktop.
json schema #cheatsheet #JSON

Here's a concise cheatsheet for JSON Schema:

Basic Structure

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://example.com/schema.json",
  "title": "Schema Title",
  "description": "Schema description",
  "type": "object"
}
{
  "type": "object",
  "properties": {
    "reasoning": {
      "type": "string"
    },
    "label": {
      "type": "string",
      "enum": ["yes", "no"]
    }
  },
  "required": [
    "reasoning",
    "label"
  ]
}

Data Types

  • "type": "string"
  • "type": "number"
  • "type": "integer"
  • "type": "boolean"
  • "type": "object"
  • "type": "array"
  • "type": "null"

String Constraints

{
  "type": "string",
  "minLength": 2,
  "maxLength": 50,
  "pattern": "^[A-Za-z]+$",
  "format": "email"
}

Number Constraints

{
  "type": "number",
  "minimum": 0,
  "maximum": 100,
  "exclusiveMinimum": true,
  "multipleOf": 5
}

Object Properties

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer" }
  },
  "required": ["name"],
  "additionalProperties": false
}

Array Constraints

{
  "type": "array",
  "items": { "type": "string" },
  "minItems": 1,
  "maxItems": 5,
  "uniqueItems": true
}

Combining Schemas

{
  "allOf": [{ ... }, { ... }],
  "anyOf": [{ ... }, { ... }],
  "oneOf": [{ ... }, { ... }],
  "not": { ... }
}

Conditional Schemas

{
  "if": { "properties": { "country": { "const": "US" } } },
  "then": { "properties": { "postal_code": { "pattern": "^[0-9]{5}(-[0-9]{4})?$" } } },
  "else": { "properties": { "postal_code": { "type": "string" } } }
}

Reusable Definitions

{
  "$defs": {
    "address": {
      "type": "object",
      "properties": {
        "street": { "type": "string" },
        "city": { "type": "string" }
      }
    }
  },
  "properties": {
    "billing_address": { "$ref": "#/$defs/address" },
    "shipping_address": { "$ref": "#/$defs/address" }
  }
}

This cheatsheet covers the most commonly used features of JSON Schema. It includes basic structure, data types, constraints for strings and numbers, object and array definitions, schema combinations, conditional schemas, and reusable definitions[1][2].

Citations: [1] https://json-schema.org/understanding-json-schema [2] https://github.com/CyberT33N/JSON-Schema-cheat-sheet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment