Search code examples
jsonjsonschema

Can JSON contained in a string property of another JSON be described via JSON schema?


If I have an object like this:

{
  "name": "John",
  "details": "{\"age\": 30, \"email\": \"[email protected]\"}"
}

Is it possible to describe nested JSON in "details" with a schema inside of an outer schema?

I imagine something like this:

{
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "details": {
      "type": "string",
      "contentMediaType": "application/json", 
      "schema": {
        "type": "object",
        "properties": {
           "age": {
             "type": "number"
           },
           "email": {
             "type": "string"
           }
        }
      }
    }
  }
}


Solution

  • Yes, if you are using the latest draft, 2020-12. See section 8. A Vocabulary for the Contents of String-Encoded Data. You already have the contentMediaType; this draft adds contentSchema.

    Note, however, that you will find very limited support in tooling for validating the decoded JSON against this schema. The spec states "[these keywords] do not function as validation assertions; a malformed string-encoded document MUST NOT cause the containing instance to be considered invalid." So, yes, you can describe the contents of the JSON string, but that description will not be validated unless your application takes further steps to perform that validation.