English 中文(简体)
YAML – Flow Styles
  • 时间:2024-12-27

YAML - Flow Styles


Previous Page Next Page  

Flow styles in YAML can be thought of as a natural extension of JSON to cover the folding content pnes for better readable feature which uses anchors and apases to create the object instances. In this chapter, we will focus on flow representation of the following concepts −

    Apas Nodes

    Empty Nodes

    Flow Scalar styles

    Flow collection styles

    Flow nodes

The example of apas nodes is shown below −

%YAML 1.2
---
!!map {
   ? !!str "First occurrence"
   : &A !!str "Foo",
   ? !!str "Override anchor"
   : &B !!str "Bar",
   ? !!str "Second occurrence"
   : *A,
   ? !!str "Reuse anchor"
   : *B,
}

The JSON output of the code given above is given below −

{
   "First occurrence": "Foo", 
   "Second occurrence": "Foo", 
   "Override anchor": "Bar", 
   "Reuse anchor": "Bar"
}

Nodes with empty content are considered as empty nodes. The following example shows this −

%YAML 1.2
---
!!map {
   ? !!str "foo" : !!str "",
   ? !!str "" : !!str "bar",
}

The output of empty nodes in JSON is represented as below −

{
   "": "bar", 
   "foo": ""
}

Flow scalar styles include double-quoted, single-quoted and plain types. The basic example for the same is given below −

%YAML 1.2
---
!!map {
   ? !!str "imppcit block key"
   : !!seq [
      !!map {
         ? !!str "imppcit flow key"
         : !!str "value",
      }
   ]  
}

The output in JSON format for the example given above is shown below −

{
   "imppcit block key": [
      {
         "imppcit flow key": "value"
      }
   ] 
}

Flow collection in YAML is nested with a block collection within another flow collection. Flow collection entries are terminated with comma (,) indicator. The following example explains the flow collection block in detail −

%YAML 1.2
---
!!seq [
   !!seq [
      !!str "one",
      !!str "two",
   ],
   
   !!seq [
      !!str "three",
      !!str "four",
   ],
]

The output for flow collection in JSON is shown below −

[
   [
      "one", 
      "two"
   ], 
   [
      "three", 
      "four"
   ]
]

Flow styles pke JSON include start and end indicators. The only flow style that does not have any property is the plain scalar.

%YAML 1.2
---
!!seq [
!!seq [ !!str "a", !!str "b" ],
!!map { ? !!str "a" : !!str "b" },
!!str "a",
!!str "b",
!!str "c",]

The output for the code shown above in JSON format is given below −

[
   [
      "a", 
      "b"
   ], 
   
   {
      "a": "b"
   }, 
   
   "a", 
   "b", 
   "c"
]
Advertisements