3
votes

I have a JSON schema file:

{  
   "id":"http://schema.acme.com/user",
   "$schema":"http://json-schema.org/draft-06/schema#",
   "definitions":{  
      "user":{  
         "description":"The name the user has selected",
         "type":"object",
         "required":[  
            "username",
            "premium"
         ],
         "properties":{  
            "username":{  
               "type":"string",
               "maxLength":10,
               "minLength":1
            },
            "premium":{  
               "type":"boolean"
            }
         }
      }
   }
}

and I want to validate this against a json object. So I create a temporary object of that type with this schema:

{  
   "id":"http://schema.acme.com/uName",
   "$schema":"http://json-schema.org/draft-06/schema#",
   "properties":{  
      "uName":{  
         "$ref":"smUserSchema.json#/definitions/user"
      }
   },
   "required":[  
      "uName"
   ]
}

and I have this JSON data file:

{  
   "uName":{  
      "username":"Bob",
      "premium":true
   }
}

The goal here is to not embed my temporary object in my JSON schema for the class type. (And yes, one of my problems here is that I'm trying to for OO techniques onto JSON. That's true, I'm just doing this for re-use and inheritance reasons, there might be a better way.)

When I go to validate this I get this error:

$ ajv -s uNameSchema.json -d validUser.json 
schema uNameSchema.json is invalid
error: can't resolve reference smUserSchema.json#/definitions/user from id http://schema.acme.com/uName#

How can I include on JSON schema in another schema?

See Also:

2

2 Answers

2
votes

You need to make sure ajv is aware of smUserSchema.json, it won't find it automatically. There's a command line option to pass dependent schemas but I can't recall it offhand. ajv --help should tell you (I don't have it readily available).

0
votes

You've set the $id of the schema you want to reference to http://schema.acme.com/user.

However, you use a relative refernece of smUserSchema.json#/definitions/user, which resolves to http://schema.acme.com/smUserSchema.json#/definitions/user.

You need to change either the $id defined in your referenced schema, or the relative URI used for $ref, so that they match.

I realise this answer is a little late, and I hope you resolved your issue before now, but it may still be useful for others.