jsonyamlswaggerjsonpointer

JSON Pointer inside JSON document: how to express in YAML?


I'm defining the Swagger specification of a REST service to be implemented. Since the response document represents a tree-like structure where several nodes repeat multiple times, I'd like to define them in the beginning of a document and then reference them by means of JSON Pointer notation.

So the response document should look like this:

{
    "definitions": {
        "organizations": [
            { "id": 101, "name": "Org 1" },
            ...
        ],        
        "clusters": [
            { "id": 201, "name": "Cluster 1" },
            ...
        ],        
        "plants": [
            { "id": 301 }
        ]
    },    
    "plants_hierarchy": {
        "relations": [
            {
                "cluster": { "$ref", "#/definitions/clusters/1" },
                "organization": { "$ref", "#/definitions/organizations/123" },                    
                "plants": [
                    { "$ref": "#/definitions/plants/234" },
                    ...
                ]
            },
            ...
        ]
    }
}

The plant objects inside #/plants_hierarchy/relations/plants should be represented as JSON Pointer and not as the original objects in order to keep the size of the document small.

My question is how should I express the JSON Pointer in the Swagger YAML document?


Solution

  • YAML provides anchors and aliases, which cover your use-case exactly:

    definitions:
      organizations:
        - &my_organization
          id: 101
          name: Org 1
      clusters:
        - &my_cluster
          id: 201
          name: Cluster 1
      plants:
         - &my_plant
           id: 301 
    plants_hierarchy:
      relations:
        - cluster: *my_cluster
          organization: *my_organization
          plants:
            - *my_plant