Allyl Isocyanate
Allyl Isocyanate

Reputation: 13616

Creating a type definition for a property named "type" using JSON schema

I'm trying to create a JSON schema for an existing JSON file that looks something like this:

{
  "variable": {
    "name": "age",
    "type": "integer"
  }
}

In the schema, I want to ensure the type property has the value string or integer:

{
  "variable": {
    "name": "string",
    "type": {
      "type": "string",
      "enum": ["string", "integer"]
    }
  }
}

Unfortunately it blows up with message: ValidationError {is not any of [subschema 0]....

I've read that there are "no reserved words" in JSON schema, so I assume a type of type is valid, assuming I declare it correctly?

Upvotes: 5

Views: 3062

Answers (2)

Walt
Walt

Reputation: 332

The accepted answer from jruizaranguren doesn't actually answer the question.

The problem is that given JSON (not JSON schema, JSON data) that has a field named "type", it's hard to write a JSON schema that doesn't choke.

Imagine that you have an existing JSON data feed (data, not schema) that contains:

"ids": [ { "type": "SSN", "value": "123-45-6789" },
         { "type": "pay", "value": "8675309" } ]

What I've found in trying to work through the same problem is that instead of putting

"properties": {
                    "type": {                 <======= validation chokes on this 
                        "type": "string"
}

you can put

"patternProperties": {
                    "^type$": {
                        "type": "string"
}

but I'm still working through how to mark it as a required field. It may not be possible.

I think, based on looking at the "schema" in the original question, that JSON schemas have evolved quite a lot since then - but this is still a problem. There may be a better solution.

Upvotes: 6

jruizaranguren
jruizaranguren

Reputation: 13597

According to the specification, in the Valid typessection for type:

The value of this keyword MUST be either a string or an array. If it is an array, elements of the array MUST be strings and MUST be unique. String values MUST be one of the seven primitive types defined by the core specification.

Later, in Conditions for successful validation:

An instance matches successfully if its primitive type is one of the types defined by keyword. Recall: "number" includes "integer".

In your case:

{
  "variable": {
    "name": "string",
    "type": ["string", "integer"]  
  }
}

Upvotes: 0

Related Questions