krg7880 / json-schema-generator

Generates draft v4 schema from a local file or a remote JSON url.
MIT License
174 stars 53 forks source link

JSON schema generation on object with an array. #37

Open Jaikant opened 1 year ago

Jaikant commented 1 year ago

The json schema generator does not generate schema the way I want it to. For e.g. When I create the schema on the object : {c: ["a", "b", "c"]}

The schema created is as below:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "description": "",
  "type": "object",
  "properties": {
    "c": {
      "type": "array",
      "items": {
        "required": [

        ],
        "properties": {

        }
      },
      "value": [
        "a",
        "b",
        "c"
      ]
    }
  },
  "required": [
    "c"
  ]
}

In the above schema - the array c, has a default value of [“a”, “b”, “c”]

Instead my requirement is that, we should create the schema as below.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "description": "",
  "type": "object",
  "properties": {
    "c": {
      "type": "array",
      "items": {
        "type": "string",
        "enum": [
          "a",
          "b",
          "c"
        ]
      }
    }
  },
  "required": [
    "c"
  ]
}
Jaikant commented 1 year ago

On testing with an array of objects: { c: [{a: 1}, {a: 2}, {a: 3}] }

The output is:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "description": "",
  "type": "object",
  "properties": {
    "c": {
      "type": "array",
      "uniqueItems": true,
      "minItems": 1,
      "items": {
        "required": [
          "a"
        ],
        "properties": {
          "a": {
            "type": "number"
          }
        }
      },
      "value": [
        {
          "a": 1
        },
        {
          "a": 2
        },
        {
          "a": 3
        }
      ]
    }
  },
  "required": [
    "c"
  ]
}

In the above output, I need the "items" to have a "type" of "object".

So it seems, the fix could be to include the "type" for array elements? If the array elements are primitives, it could skip adding the "required" and "properties"?