yaml Using anchors and aliases for transcluded content Using YAML merge-keys to cross-reference rows from another YAML table

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

    ---
    person_table:
      - &person001
        fname:  homer
        lname:  simpson
        role:   dad
        age:    33

      - &person002
        fname:  marge
        lname:  simpson
        role:   mom
        age:    34

      - &person003
        fname:  peter
        lname:  griffin
        role:   dad
        age:    34
        
    motto_table:
      - &motto001
        <<: *person001
        motto: >
          D'oh!! YAML is too complicated!

      - &motto002
        <<: *person002
        motto: >
          Bart! Listen to your father!

      - &motto003
        <<: *person003
        motto: >
          Hey! YAML is freakin' sweet!

Problem

  • developer wishes to cross-reference rows-with-anchors from one table and link to them with rows-as-aliases in another table
  • developer wishes to avoid creating the "nested dictionaries problem"

Solution

  • use YAML aliases, with YAML merge keys
  • in YAML, reusable "transclusion identifiers" are called anchors and aliases
  • in YAML, reusable "transclusion identifiers" consist of alphanumeric tokens preceeded by an ampersand or asterisk

Rationale

  • YAML anchors and aliases allow for increased data normalization
  • YAML anchors and aliases enforce DRY (Don't repeat yourself)
  • in this example, a table structure can be designed and preserved which closely coincides with a database
  • in this example, data entry and file sizes can be reduced

Pitfalls

  • in this specific example, yaml.load() will produce nested dictionaries
    • under the person name-value pair, the value for person will be a sub-dictionary
    • this may be undesirable, because it breaks the uniformity of the table structure
  • failure to correctly specify aliases will result in missing data
    • (typos will create broken cross-references)
  • YAML does not support file transclusion by reference, so all aliases and anchors must exist in the same yaml file
  • not all YAML parsers reliably support anchors and aliases

See also



Got any yaml Question?