2020年9月3日星期四

Introduction Of YAML

 YAML(Ain't  Markup Language) is a human-readable data serialization language.

It is commonly used for configuration files and in applications where data is being stored for transmitted.

It uses both Python-style indentations to indicate nesting and a more compact format that uses [...] for lists and {...} for maps making YAML 1.2 a superset of JSON.

YAML natively encodes scalars(such as strings, integers, and floats), lists, and associative arrays(also known as maps, dictionaries, or hashes).

YAML is intended to be read and written in streams, a feature inspired bySAX.

Syntax

  • Whitespace indentation. Not tab characters.
  • Comments begin with #. Can start anywhere, without inside of a string.
  • List members are denoted by -, and a list can be specified by square brackets[...] (like JSON).
  • An associative array entry is represented using colon space in the form key: value.
    • A question mark can be used in front of a key, like "?key: value" to allow the key to containing leading dashes, square brackets, etc., without quotes.
    • An associative array can also be specified in curly braces{...}, for JSON compatibility.
- {name: John Smith, age: 33}  # A list of key-value objects.
- name: Mary Smith
  age: 27
- [name, age]: [Rae Smith, 4]   # sequences as keys are supported
--- # People, by gender
men: [John Smith, Bill Jones]  # first type of single item list.
women:                        # second type of single item list.
  - Mary Smith
  - Susan Williams
Objects and lists are important components in yaml and can be mixed.
The second lists them by gender; it is a key-value object containing two lists.
  • Block scalars are delimited with indentation with optional modifiers to preserve (|) or fold (>) newlines. eg:

data: |
   There once was a tall man from Ealing
   Who got on a bus to Darjeeling
       It said on the door
       "Please don't sit on the floor"
   So he carefully sat on the ceiling
data: >
   Wrapped text
   will be folded
   into a single
   paragraph

   Blank lines denote
   paragraph breaks
  • Multiple documents within a single stream are separated by three hyphens(---)
    • Three periods(...) optionally end a document within a stream.
  • Repeated nodes are initially denoted by an ampersand(&) and thereafter referenced with an asterisk(*).
  • Nodes may be labeled with a type or tag using the exclamation point(!!) followed by a string, which can be expanded into a URL.
  • YAML documents in a stream may be preceded by 'directives' composed of a percent sign(%) followed by a name and space-delimited parameters. Two directives are defined in YAML 1.1
  • Two additional sign characters are reserved in YAML for possible future specification: the at sign @ and backtick `.

Advanced components

#define anchor and references.
--- # Sequencer protocols for Laser eye surgery
- step:  &id001                  # defines anchor label &id001
    instrument:      Lasik 2000
    pulseEnergy:     5.4
    pulseDuration:   12
    repetition:      1000
    spotSize:        1mm

- step: &id002
    instrument:      Lasik 2000
    pulseEnergy:     5.0
    pulseDuration:   10
    repetition:      500
    spotSize:        2mm
- step: *id001                   # refers to the first step (with anchor &id001)
- step: *id002                   # refers to the second step
- step: *id002
#YAML autodetects the datatype of the entity,

a: 123                     # an integer
b: "123"                   # a string, disambiguated by quotes
c: 123.0                   # a float
d: !!float 123             # also a float via explicit data type prefixed by (!!)
e: !!str 123               # a string, disambiguated by explicit type
f: !!str Yes               # a string via explicit type
g: Yes                     # a boolean True (yaml1.1), string "Yes" (yaml1.2)
h: Yes we have No bananas  # a string, "Yes" and "No" disambiguated by context.

Comparison with JSON

JSON syntax is a basis of YAML version 1.2,
most JSON documents can be parsed by some YAML parsers such as Syck.
YAML has many additional features lacking in JSON, including comments, extensible data types, relational anchors, strings without quotation marks, and mapping types preserving key order.

Basic deserialization

contact.yml:
    name: Nathan Sweet
    age: 28
    address: 4011 16th Ave S
    phone numbers:
     - name: Home
       number: 206-555-5138
     - name: Work
       number: 425-555-2306

In Java:
    YamlReader reader = new YamlReader(new FileReader("contact.yml"));
    Object object = reader.read();
    System.out.println(object);
    Map map = (Map)object;
    System.out.println(map.get("address"));

Multiple objects

contact2.yml
    name: Nathan Sweet
    age: 28
    ---
    name: Some One
    age: 25
In Java:
    YamlReader reader = new YamlReader(new FileReader("contact.yml"));
    while (true) {
    	Map contact = reader.read();
    	if (contact == null) break;
    	System.out.println(contact.get("age"));
    }
#print: 
28
25

Deserializing other classes

contact2.yml
    name: Nathan Sweet
    age: 28
JavaBean:
    public class Contact {
    	public String name;
    	public int age;
    }
Deserializing to object instance:
    YamlReader reader = new YamlReader(new FileReader("contact.yml"));
    Contact contact = reader.read(Contact.class);
    System.out.println(contact.age);
print result:
    !com.example.Contact
    name: Nathan Sweet
    age: 28

Serializing objects

    Contact contact = new Contact();
    contact.name = "Nathan Sweet";
    contact.age = 28;
    YamlWriter writer = new YamlWriter(new FileWriter("output.yml"));
    writer.write(contact);
    writer.close();
Print output.yml:
    !com.example.Contact
    name: Nathan Sweet
    age: 28

yamlReader uses an ArrayList by default.
    List list = new ArrayList();
    list.add("moo");
    list.add("cow");
    - moo
    - cow
If the list was a LinkedList, then YamlWriter knows that a tag is needed and outputs:
    List list = new LinkedList();
    list.add("moo");
    list.add("cow");
    !java.util.LinkedList
    - moo
    - cow

Tag shortcuts

    YamlWriter writer = new YamlWriter(new FileWriter("output.yml"));
    writer.getConfig().setClassTag("contact", Contact.class);
    writer.write(contact);
    writer.close();

The output no longer contains the full class name for the Contact class.

    !contact
    name: Nathan Sweet
    age: 28

Lists and maps

When reading or writing a List or Map, YamlBeans cannot know what type of objects are supposed to be in the List or Map, so it will write out a tag.
    !com.example.Contact
    name: Bill
        phoneNumbers:
            - !com.example.Phone
              number: 206-555-1234
            - !com.example.Phone
              number: 206-555-5678
            - !com.example.Phone
              number: 206-555-7654
This can make the YAML less readable. To improve this, you may define what element type should be expected for a List or Map field on your object.
    YamlWriter writer = new YamlWriter(new FileWriter("output.yml"));
    writer.getConfig().setPropertyElementType(Contact.class, "phoneNumbers", Phone.class);
    writer.write(contact);
    writer.close();
Now YamlBeans knows what to expect for elements of the "phoneNumbers" field, so extra tags will not be output.
    !com.example.Contact
    name: Bill
        phoneNumbers:
            - number: 206-555-1234
            - number: 206-555-5678
            - number: 206-555-7654
Setting the element type for a Map field tells YamlBeans what to expect for values in the Map. Keys in a Map are always Strings.


没有评论: