Sunday 3 June 2018

YAML: Reuse a block of code (merging)

The "<<" merge key is used to indicate that all the keys of one or more specified maps should be inserted into the current map

For example, consider below employee instance of the organization ‘ABC labs’.

employee.yml
--- 
firstName: Krishna
id: 1
lastName: MP
organization: 
  city: Bangalore
  organizationName: "ABC labs"

Suppose, you are writing a service that return all the employees in the organisation ‘ABC labs’, it looks like below.
--- 
- 
  firstName: Krishna
  id: 1
  lastName: MP
  organization: 
    city: Bangalore
    organizationName: "ABC labs"
- 
  firstName: Chamu
  id: 2
  lastName: Kb
  organization: 
    city: Bangalore
    organizationName: "ABC labs"
As you observe the above yaml information, ‘organization’ details are repeated here.

YAML provides << (merge key) that is used to reuse the block of information.

For example,

employee.yaml

---
- id: 1
  firstName: "Krishna"
  lastName: "MP"
  organization: &ABCOrg
    organizationName: "ABC labs"
    city: "Bangalore"
- id: 2
  firstName: "Chamu"
  lastName: "Kb"
  <<: *ABCOrg


As you see above example, I created a reference ‘&ABCOrg’ and reused this reference in all the places.

You can test the result at ‘http://www.yamllint.com/’.


When I click on ‘Go’ button, it is changed like below.





Previous                                                 Next                                                 Home

No comments:

Post a Comment