Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

jsonschema - Is there support in JSON Schema for deep object validation?

I was looking around the docs and couldn't find any direct or indirect solution.

Is there any way to get validation on JSON objects without knowing exactly where the specific object is located?

For example, I want to validate the following sub-object:

{
  "grandParent": {
    "parent": {
      "child": {
        "name": "John"
      }
    }
  }
}

The object can be part of a larger JSON file the can be structured as follows:

{
  "root": {
    "someKey": {
      "grandParent": ...
    },
    "grandParent": ...,
    ...<go in even deeper>: {
      "grandParent": ...
    }
  }
} 

Can I create a json schema that validates the object no matter where it is?

Similar example in glob would be: root.**.grandParent.parent.child

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll need to use a combination of additionalProperties, items, and recursive references.

First, we define the structure you want to validate. You have to define properties for each layer of the object.

Next, you want your root level to reference that definition. Because you're using pre draft 2019-09, you'll need to wrap that reference in an allOf.

Then you want to make sure that for objects, the values have the root schema applied, and for arrays, each item has the root schema applied.

The use of "$ref": "#" resolves to the root of the schema, which creates the cyclical reference.

Some implementations may not like this, but most should be able to handle it.

Here's a live demo of the below schema: https://jsonschema.dev/s/lBrZk

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "definitions": {
    "grandParentToChild": {
        "properties": {
          "grandParent": {
            "properties": {
              "parent": {
                "properties": {
                  "child": {
                    "properties": {
                      "name": {
                        "type": "string"
                      }
                    }
                  }
                }
              }
            }
          }
        }
    }
  },
  "allOf": [
    {
      "$ref": "#/definitions/grandParentToChild"
    }
  ],
  "additionalProperties": {
    "$ref": "#"
  },
  "items": {
    "$ref": "#"
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...