How to manage multiple JSON schema files?

前端 未结 1 858
名媛妹妹
名媛妹妹 2020-12-08 02:42

I\'m trying to validate my JSON API using node.js + json-schema.js from commonjs-utils. Just single validation was easy but could not find right way how to manage multiple s

相关标签:
1条回答
  • 2020-12-08 03:01

    In JSON Schemas, you can either put a schema per file and then access them using their URL (where you stored them), or a big schema with id tags.

    Here is for one big file:

    {
        "id": "#root",
        "properties": {
            "author": {
                "id": "#author",
                "properties": {
                    "first_name": {
                        "type": "string"
                    },
                    "last_name": {
                        "type": "string"
                    }
                },
                "type": "object"
            },
            // author
            "author_api": {
                "id": "#author_api",
                "items": {
                    "$ref": "author"
                },
                "type": "array"
            },
            // authors API
            "book": {
                "id": "#book",
                "properties": {
                    "author": {
                        "type": "string"
                    },
                    "title": {
                        "type": "string"
                    }
                },
                "type": "object"
            },
            // books API: list of books written by same author
            "books_api": {
                "id": "#books_api",
                "properties": {
                    "author": {
                        "$ref": "author"
                    },
                    "books": {
                        "items": {
                            "$ref": "book"
                        },
                        "type": "array"
                    }
                },
                "type": "object"
            }
        }
    }
    

    You can then reference your validator to one of those sub schemas (which are defined with an id).

    From outside of your schema, this:

    { "$ref": "url://to/your/schema#root/properties/book" }
    

    is equivalent to this:

    { "$ref": "url://to/your/schema#book" }
    

    … which is equivalent, from inside, to this:

    { "$ref": "#root/properties/book" }
    

    or this (still from inside):

    { "$ref": "#book" }
    

    See my answer here for more information.

    0 讨论(0)
提交回复
热议问题