1, the JSON?

JSON(JavaScript Object Notation) is a lightweight data interchange format. It is concise, readable and supports a wide range of features.

Below we use JSON to describe the basic information of a commodity, including some basic data types of JSON.

{
  "productId": 1."productName": "HUAWEI Mate X2"."price": 17999."tags": [ "Kill"."Proprietary"]}Copy the code

2, Json Schema?

JSON Schema is a vocabulary that allows you to annotate and validate JSON documents.

JSON Schema is a solution that helps you define, validate, and even repair JSON data formats. It defines a set of rules that allow us to describe the data format of a JSON string by defining a schema(itself JSON).

Let’s use Json Schem to describe the above commodity information. Also specify the JSON properties that we need to constrain.

{
  "type": "object"."title": "Mobile phone goods"."description": "Mobile Product Details"."properties": {
    "productId": {
      "description": "Product id"."type": "integer"
    },
    "productName": {
      "description": "Trade Name"."type": "string"
    },
    "price": {
      "description": "Commodity prices"."type": "number"."exclusiveMinimum": 0
    },
    "tags": {
      "description": "Commodity Label"."type": "array"."items": {
        "type": "string"
      },
      "minItems": 1."uniqueItems": true}},"required": ["productId"."productName"."price"]}Copy the code

Let’s briefly examine the JSON Schema above.

  • {}
{
  "type": "object".// The constraint object is object,
  "title": "Mobile phone goods".//
  "description": "Mobile Product Details".// The description is optional
  "properties": {...// Here are the constraints on specific attributes in object
  },
  "required": ["productId"."productName"."price"] // The current data object must contain the productId, productName, and price fields
}
Copy the code
  • productId
"productId": {
      "description": "Product id"."type": "integer"  // constraints productid attribute type is an integer
   }
Copy the code
  • productName
 "productName": {
      "description": "Trade Name"."type": "string"  Constraint productName attribute type is character
    },
Copy the code
  • price
"price": {
      "description": "Commodity prices"."type": "number".// Constrain the price attribute type to be an integer or floating-point.
      "exclusiveMinimum": 0 // Constrain the number >0 (not including 0)
    },
Copy the code
  • tags
 "tags": {
      "description": "Commodity Label"."type": "array".// Constraint tag attributes are arrays
      "items": {
        "type": "string" // Items is an array item constraint, where the array items are characters
      },
      "minItems": 1.// Constrain the array to contain at least one item
      "uniqueItems": true // Each item in the array must not be repeated
    }
Copy the code

From the examples above, I believe you should have a preliminary understanding of Json Schema. For more information about Json Schema keywords, see the Json Schema specification.

3. Json Schema application

1. Data verification.

In real business development we often have scenarios where large amounts of data are validated. For example, form submission in backend systems, automated interface testing, and so on.

The recommendation here is ajv.js, a high-performance JSON validator for Node.js and browsers.

Simple example CodePen.

import Ajv from "ajv"
const ajv = new Ajv()
// JSON Schema
const schema = {
	  ...
}
const validate = ajv.compile(schema)
// Data to be validated
const validData = {
   ...
}
const validResult = validate(validData)
if (validResult) {
  console.log('Verified')}else {
  console.log(validate.errors) // Error details
}
Copy the code
2. Automatic form generation scheme based on JSON Schema.

Is there any way to ensure that the data is correct when the data is input?

Through the observation of JSON Schema, we can find that each Schema data can correspond to a form UI display. The UI logic of the form ensures that the data complies with Schema rules before submitting the form. After the form is verified, the JSON data complies with Schema constraints.

Here are a few libraries that I have researched in real development and that are up front on Github.

1, the react

  • react-jsonschema-form

  • FormRender provides a visual JSON Schema generation tool. Click the link

2, the vue

  • Vue-json-schema-form provides a visual JSON schema generation tool. Click the link

The other libraries allow developers to implement custom templates that extend form components encapsulated in business development to JSON Schema constraint specifications.

3: Other fun libraries
  • typescript-json-schema

    By adding comment keywords to TypeScript files. Generate JSON Schema based on TS code. Supports both use as a command line tool and invocation from code.

    Next, we use TS to describe the above commodity information

    export interface Product {
      / * * *@minimum 0
       * @TJS-type integer
       */
      productId: number;
      productName: string;
      / * * *@exclusiveMinimum 0 * /
      price: number;
      / * * *@minItems 1
       *  @uniqueItems  true* /
      tags: Array<string>
    }
    Copy the code

    run

    > npx typescript-json-schema 'index.ts' 'Product' -o test.json 
    Copy the code

    The JSON Schema file we defined above is available in the output file.

    Thank you for reading this article at the end. If you have a better application of JSON Schema, feel free to leave a comment in the comments section.