laitimes

Say goodbye to cumbersome data validation: simplify your code with JSON Schema

author:Flash Gene
Say goodbye to cumbersome data validation: simplify your code with JSON Schema

1. JSON Schema

JSON Schema is a JSON-based format that describes the structure of JSON data and validates JSON data. It provides a clear description of JSON data that can be used to validate, document, and define. Here's a closer look at some of the core features of JSON Schema and how to apply them:

  1. Describe the data format: Using the JSON Schema, you can describe in detail the expected structure of your JSON data, including which fields are required, what the data type of the field is (e.g., string, number, boolean, etc.), and other properties of the field (e.g., minimum length, maximum length of string, regular expression pattern, etc.).
  2. Data validation: One of the most common uses of JSON schemas is to validate JSON data. This means that you can check that the JSON data is in the expected format against the defined schema, which is especially useful when working with external data or API responses. If the data isn't as expected, you can catch these errors and act on them accordingly.
  3. Auto-generated documentation: Since the JSON Schema describes the structure of the data in a standardized format, it can be used to automatically generate documentation. This is especially useful for documenting APIs, as developers have a clear understanding of what kind of data the API interface expects to receive, and what kind of data will be returned in response to the API.
  4. Simplify the development process: By using JSON Schema to validate data, developers can reduce the amount of code they manually write for data validation. This not only improves development efficiency, but also reduces bugs due to data errors.
  5. Cross-language support: JSON Schema has a wide range of programming language support, including but not limited to JavaScript, Python, Java, and C#. This means that no matter what programming language you're using, you'll find libraries to help you with JSON schemas.
  6. Versioning: The JSON Schema itself is also evolving, and there are currently multiple versions. Each release adds new features and improves existing ones. This allows the JSON schema to adapt to changing needs while maintaining backward compatibility.

By using JSON Schema, developers can create more robust and reliable applications that ensure data consistency and accuracy, while improving development efficiency and reducing maintenance costs.

2. Birth Background

JSON Schema was born out of the widespread adoption of the JSON data format and the consequent need to validate the structure and content of JSON data. JSON (JavaScript Object Notation) is a lightweight data exchange format that is easy for humans to read and write, as well as easy for machines to parse and generate. With the rapid development of web services and application programming interfaces (APIs), JSON has become a popular way to exchange data on the web.

Against this backdrop, developers and system architects are faced with the challenge of validating JSON data effectively, especially in complex systems and cross-team collaboration, where it becomes even more important to ensure data consistency and correctness. Here are a few key contextual factors for the emergence of JSON schemas:

  1. Data validation needs: As systems become more reliant on dynamic and flexible data exchange, there is a need for a reliable way to validate data structures and content to prevent problems caused by incorrect data.
  2. Automation and standardization: In automated processes, such as API calls and responses, there needs to be a standard way to describe and validate data, reducing human intervention and potential errors.
  3. Cross-language and cross-platform interactions: As a language-agnostic data format, JSON is widely used for interactions between different programming languages and platforms. JSON Schema provides a unified way to define and validate data structures, facilitating interoperability between different systems.
  4. Documentation and collaboration: The JSON Schema can also be used as a document to help developers understand the structure of the data model and facilitate communication and collaboration among team members.

As a result, JSON Schema has become an integral part of modern web development by not only solving the problem of data validation, but also supporting a variety of uses such as document generation, automated testing, and integration of development tools.

3. TS vs JSON Schema

Both JSON Schema and TypeScript (TS) are used to ensure the correctness of the data structure, but there are some key differences in their application and purpose:

  1. Applications:
  2. JSON Schema: It is used to describe and validate JSON data structures to ensure that JSON data conforms to predefined formats. It is independent of programming language and can be used for data verification in network transmission, configuration file verification, and other scenarios.
  3. TypeScript: is a superset of JavaScript that adds the ability to define static types. TypeScript is mainly used to check for type errors in code at compile time, improving development efficiency and code quality.
  4. Timing of execution:
  5. JSON Schema: Typically used at runtime to validate data, such as validating data structures for API requests/responses.
  6. TypeScript: Type checking at compile time, and the compiled code is converted to normal JavaScript without type checking at runtime.
  7. Purpose and Usage Scenarios:
  8. JSON Schema: Used to ensure that data adheres to a specific format and structure, and is commonly used for API data exchange and configuration data validation.
  9. TypeScript: It aims to improve the maintainability and readability of code by introducing a static type system, and is mainly used in the development phase to help developers catch type-related errors.
  10. Languages & Platforms:
  11. JSON Schema: is a stand-alone specification that can be used with any programming language that supports JSON.
  12. TypeScript: is a programming language that requires a specific compiler (TypeScript compiler) to convert TypeScript code into JavaScript code.

JSON Schema focuses on data validation at runtime to ensure the correctness of data structures, while TypeScript focuses on compile-time type checking to improve code quality and security during development. The two, while complementary in some ways, serve different stages and aspects of programming and data processing.

4. Examples

4.1 Minimal Examples

{
  "$id": "https://example.com/person.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Person",
  "type": "object",
  "properties": {
    "firstName": {
      "type": "string",
      "description": "The person's first name."
    },
    "lastName": {
      "type": "string",
      "description": "The person's last name."
    },
    "age": {
      "description": "Age in years which must be equal to or greater than zero.",
      "type": "integer",
      "minimum": 0
    }
  }
}
           

Data:

{
  "firstName": "John",
  "lastName": "Doe",
  "age": 21
}
           

4.2 Arrays

{
  "$id": "https://example.com/arrays.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "description": "A representation of a person, company, organization, or place",
  "type": "object",
  "properties": {
    "fruits": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "vegetables": {
      "type": "array",
      "items": { "$ref": "#/$defs/veggie" }
    }
  },
  "$defs": {
    "veggie": {
      "type": "object",
      "required": [ "veggieName", "veggieLike" ],
      "properties": {
        "veggieName": {
          "type": "string",
          "description": "The name of the vegetable."
        },
        "veggieLike": {
          "type": "boolean",
          "description": "Do I like this vegetable?"
        }
      }
    }
  }
}
           

Data:

{
  "fruits": [ "apple", "orange", "pear" ],
  "vegetables": [
    {
      "veggieName": "potato",
      "veggieLike": true
    },
    {
      "veggieName": "broccoli",
      "veggieLike": false
    }
  ]
}
           

4.3 枚举

{
  "$id": "https://example.com/enumerated-values.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Enumerated Values",
  "type": "object",
  "properties": {
    "data": {
      "enum": [42, true, "hello", null, [1, 2, 3]]
    }
  }
}
           

Data:

{
  "data": [1, 2, 3]
}
           

4.4 Regex

{
  "$id": "https://example.com/regex-pattern.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Regular Expression Pattern",
  "type": "object",
  "properties": {
    "code": {
      "type": "string",
      "pattern": "^[A-Z]{3}-\\d{3}#34;
    }
  }
}
           

Data:

{
  "code": "ABC-123"
}
           

4.5 Nesting

{
  "$id": "https://example.com/complex-object.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Complex Object",
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "age": {
      "type": "integer",
      "minimum": 0
    },
    "address": {
      "type": "object",
      "properties": {
        "street": {
          "type": "string"
        },
        "city": {
          "type": "string"
        },
        "state": {
          "type": "string"
        },
        "postalCode": {
          "type": "string",
          "pattern": "\\d{5}"
        }
      },
      "required": ["street", "city", "state", "postalCode"]
    },
    "hobbies": {
      "type": "array",
      "items": {
        "type": "string"
      }
    }
  },
  "required": ["name", "age"]
}
           

Data:

{
  "name": "John Doe",
  "age": 25,
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "state": "NY",
    "postalCode": "10001"
  },
  "hobbies": ["reading", "running"]
}
           

4.6 Conditional Verification

{
  "$id": "https://example.com/conditional-validation-dependentRequired.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Conditional Validation with dependentRequired",
  "type": "object",
  "properties": {
    "foo": {
      "type": "boolean"
    },
    "bar": {
      "type": "string"
    }
  },
  "dependentRequired": {
    "foo": ["bar"]
  }
}
           
{
  "$id": "https://example.com/conditional-validation-dependentSchemas.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Conditional Validation with dependentSchemas",
  "type": "object",
  "properties": {
    "foo": {
      "type": "boolean"
    },
    "propertiesCount": {
      "type": "integer",
      "minimum": 0
    }
  },
  "dependentSchemas": {
    "foo": {
      "required": ["propertiesCount"],
      "properties": {
        "propertiesCount": {
          "minimum": 7
        }
      }
    }
  }
}
           
{
  "$id": "https://example.com/conditional-validation-if-else.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Conditional Validation with If-Else",
  "type": "object",
  "properties": {
    "isMember": {
      "type": "boolean"
    },
    "membershipNumber": {
      "type": "string"
    }
  },
  "required": ["isMember"],
  "if": {
    "properties": {
      "isMember": {
        "const": true
      }
    }
  },
  "then": {
    "properties": {
      "membershipNumber": {
        "type": "string",
        "minLength": 10,
        "maxLength": 10
      }
    }
  },
  "else": {
    "properties": {
      "membershipNumber": {
        "type": "string",
        "minLength": 15
      }
    }
  }
}
           

5. Validators

JS can use ajv:

Say goodbye to cumbersome data validation: simplify your code with JSON Schema
// or ESM/TypeScript import
import Ajv from "ajv";
// Node.js require:
const Ajv = require("ajv");

const ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}

const schema = {
  type: "object",
  properties: {
    foo: { type: "integer" },
    bar: { type: "string" },
  },
  required: ["foo"],
  additionalProperties: false,
};

const data = {
  foo: 1,
  bar: "abc",
};

const validate = ajv.compile(schema);
const valid = validate(data);
if (!valid) console.log(validate.errors);
           

For other platforms, please refer to the official website:

Say goodbye to cumbersome data validation: simplify your code with JSON Schema

Source-WeChat public account: good friend Leping

Source: https://mp.weixin.qq.com/s/G8RdfUpUjTYWtsFHdLIniw