简体   繁体   中英

Json Schema different input formats

I'm creating some models in AWS API Gateway. I'm having problems with one that I wish it receives 2 input formats: one of the formats is just a dictionary the other is an array of dictionaries:

{
    "id":"",
    "name":""
}

and

[
    {
        "id":"",
        "Family":""
    },
    {
        "id":"",
        "Family":""
    },

    ...

    {
        "id":"",
        "Family":""
    }
]

Until now I've created the model to accept only the dictionary way:

{  
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Update",
  "type": "object",
  "properties": {
      "id": { "type": "string"},
      "name": { "type": "string"}
  },
  "required": ["id"]
}

Can you give me some tips to create the array of dictionaries, please. I've done some research and I found nothing but I'm following the way of the keywords oneOf and anyOf but I'm not sure.

You're on the right track with anyOf . What you should do depends on the similarity between the object (dictionary) that's by itself and the object that's in the array. They look different in your example, so I'll answer in kind, then show how to simplify things if they are in fact the same.


To use anyOf , you want to capture the keywords that define your dictionary

{
  "type": "object",
  "properties": {
    "id": { "type": "string"},
    "name": { "type": "string"}
  },
  "required": ["id"]
}

and wrap that inside an anyOf right at the root level of the schema

{  
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Update",
  "anyOf": [
    {
      "type": "object",
      "properties": {
        "id": { "type": "string"},
        "name": { "type": "string"}
      },
      "required": ["id"]
    }
  ]
}

To write a schema for an array of the same kind object, you need the items keyword.

{
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "id": { "type": "string"},
      "Family": { "type": "string"}
    },
    "required": ["id"]
  }
}

Add this in as a second element in the anyOf array, and you're golden.


If your lone object can have the same schema as your array-element object, then you can write that schema once as a definition and reference it in both places.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Update",
  "definitions": {
    "myObject": {
      "type": "object",
      "properties": {
        "id": { "type": "string"},
        "name": { "type": "string"}
      },
      "required": ["id"]
    }
  },
  "anyOf": [
    { "$ref": "#/definitions/myObject" },
    {
      "type": "array",
      "items": { "$ref": "#/definitions/myObject" }
    }
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM