user3384231
user3384231

Reputation: 4053

JSON Schema: Combine multiple references

My Json Schema

{
  "$schema": "http://json-schema.org/draft-07/schema#",
    
  "definitions": {
    
    "userInfo": {
      "type": "object",
      "properties": {
        "firstName": { "type": "string" },
        "lastName":  { "type": "string" },
        "emailAddress":{ "type": "string" }
      },
      "required": ["firstName", "lastName", "emailAddress"]
    },
    
    "userPassword": {
      "type": "object",
      "properties": {
        "password": { "type": "string" },
        "confirmPassword":  { "type": "string" }
      }
    }
  },

  "type": "object",
    
  "properties": {
    "standaloneDeveloper": {
      "$ref": "#/definitions/userInfo",
      "$ref": "#/definitions/userPassword"
    } 
  }
}

Data is always getting overwritten with #/definitions/userPassword

I am getting the following output with this schema

{
  "standaloneDeveloper": {
    "password": "ABCDEFGHIJKLMNOPQRSTUVWXYZABC",
    "confirmPassword": "ABCDEFGHIJKLMNOPQRSTUVWXYZABC"
  }
}

Expected output

{
  "standaloneDeveloper": {
    "firstName": "ABCDEFGHIJKLMNOPQRSTUVWXYZABC",
    "lastName": "ABCDEFGHIJKLMNOPQRSTUVWXYZABC",
    "emailAddress": "ABCDEFGHI",
    "password": "ABCDEFGHIJKLMNOPQRSTUVWXYZABC",
    "confirmPassword": "ABCDEFGHIJKLMNOPQRSTUVWXYZABC"
  }
}

How can I combine userInfo and userPassword?

Upvotes: 4

Views: 2370

Answers (1)

Jason Desrosiers
Jason Desrosiers

Reputation: 24489

In JSON (and therefore JSON Schema as well) you can't have duplicate property names. You can use allOf to get around this.

"properties": {
  "standaloneDeveloper": {
    "allOf": [
      { "$ref": "#/definitions/userInfo" },
      { "$ref": "#/definitions/userPassword" }
    ]
  }
}

This way each object has only one $ref in it.

Upvotes: 7

Related Questions