json schema for dynamic array

2019-08-27 20:35发布

问题:

I have the following json

    {
        "Dettype": "QTY",
 "Details": [
     {
  "12568": {
    "Id": 12568,
    "qty":1,
    "Freq":"2",
    "Option": 0,
    "promote":"yes"
  },
  "22456": {
    "Id": 22456,
    "qty":2,
    "Freq":"3",
    "Option": 1,
    "promote":"no"
  }
     }
 ]
}

For the above json i need to write a json schema file which will valdiates the request.

but the problem is in array the key value for each item changes dynamically. If it is some constant value i can write but don't how to do the dynamic pattern

JSON schema i got

{
"type": "object",
"additionalProperties": true,
"properties": {
    "Dettype": {
        "type": "string"
    },
    "Details": {
        "type": "array",
        "items": {
            "type": "object",
            "additionalProperties": true,
            "properties": {
                "**DYNAMIC VALUE**": {
                    "type": "object",
                    "additionalProperties": true,
                    "properties": {
                        "Id": {
                            "type": "integer"
                        },
                        "qty": {
                            "type": "integer"
                        },
                        "Freq": {
                            "type": "string"
                        },
                        "Option": {
                            "type": "integer"
                        },
                        "promote": {
                            "type": "string"
                        }
                    }
                }
            }
        }
    }
}

}

Can some one tell what changes need to be done for schema

回答1:

This is what patternProperties is for.

Here it seems your object member keys are always digits; therefore you can write things like this:

"type": "object",
"patternProperties": {
    "^\\d+$": {
        "type": "object",
        "etc": "etc"
    }
}


回答2:

You can also use additionalProperties if you want all properties to match some schema:

{
  "type": "object",
  "additionalProperties": {
    "type": "object",
    "etc": "etc"
  }
}