jsonjsonschemajson-schema-validatorjsonschema2pojo

How to Define JSON Schema for a JSON String Field in an Object?


I have a JSON object where one of the fields contains a JSON string. I need to write a JSON schema that validates this JSON string field. Here's an example of the JSON object I'm working with:

{
  "id": 1,
  "name": "John Doe",
  "details": "{\"age\": 30, \"email\": \"john.doe@example.com\"}"
}

"details" is a string which has a JSON object. I want to validate details to have a specific structure.

JSON schema that i have so far :

"type": "object",
  "properties": {
    "id": {
      "type": "integer"
    },
    "name": {
      "type": "string"
    },
    "details": {
      "type": "string",
<Schema to add validation>

How do I approach this to be handled in JSON schema itself?


Solution

  • This can be done with the keyword contentSchema but this keyword is only an annotation and not required to be used for validation by the spec. It's possible an implementation could enforce the schema defined.

    Use of JSON Schema Draft 2019-09 or newer is required.

    {
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "properties": {
      "details": { 
        "type": "string",
        "contentMediaType": "application/json",
        "contentSchema": {
          "type": "object",
          "properties": {
            "age": { "type": "integer" },
            "email": { "type": "string" }
          }
         }
       }
      }
    }