Reputation: 33
The two variants of my JSON response are:
{
firstName: "abc",
LastName: "xyz",
Address: "abc123"
}
and
{
firstName: undefined,
LastName: undefined,
Address: undefined
}
Even though defined JSON Schema as:
var ResponseSchema = {
"firstName": {
"type": [String,undefined],
},
"LastName": {
"type": [String,undefined],
},
"Address": {
"type": [String,undefined],
},
"required": [
"firstName",
"LastName",
"Address",
],
}
Response Object:
{
firstName: undefined,
LastName: undefined,
Address: undefined
}
getting an error as:
requires property "firstName"
requires property "LastName"
requires property "Address"
using "jsonschema" Node package.
Upvotes: 3
Views: 6905
Reputation: 166
You can use anyOf
to select between two schemas
https://json-schema.org/understanding-json-schema/reference/combining.html#id6
"ResponseSchema": {
"anyOf": [
{
"properties": {},
"type": "object"
},
{
"additionalProperties": false,
"properties": {
"firstName": {
"type": "string"
},
"LastName": {
"type": "string"
},
"Address": {
"type": "string"
}
},
"required": [
"firstName",
"LastName",
"Address"
],
"type": "object"
}
]
}
equivalent TypeScript type
type ResponseSchema = {
firstName: string
LastName: string
Address: string
} | {}
Also undefined
is not a type in JSON, so i have assumed the responses to be
either
{
firstName: "abc",
LastName: "xyz",
Address: "abc123"
}
or
{}
Upvotes: 0
Reputation: 5815
First: Use proper type names in your schema (strings)
You want to write a JSON schema. According to the definition, your type
can either be a string or an array of strings. What you do is pass a TypeScript type definition in, not a string.
Try
"firstName": {
"type": ["string", "null"],
},
"LastName": {
"type": ["string", "null"],
},
"Address": {
"type": ["string","null"],
},
"required": [
"firstName",
"LastName",
"Address",
]
Second: undefined
is not a valid type for a JSON schema
Having a property set to undefined
is counted as that property not being set. I'd suggest you move to null
for cases like that.
Upvotes: 4
Reputation: 12315
null
is a valid type in JSON, and so is in JSON Schema.
I don't know typescript, but here's a JSON Schema as an example.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"a": {
"type": [
"string",
"null"
]
}
},
"required": [
"a"
]
}
And as an instance JSON, this would pass validation:
{
"a": null
}
Upvotes: 0
Reputation: 3153
I don't know jsonschema, but your definition and your required fields look some kind of conceptual error to me.
You define
"required": [
"firstName",
"LastName",
"Address"
]
but set the type of every field to String,undefined
. If you now set them to undefined
the requirement is not met.
With other words: jsonschema seems to work, as it throws that error for your response:
{
"firstname": undefined,
"Lastname": undefined,
"Address": undefined,
}
Upvotes: 0