NimYAML Home Testing Ground Docs: Overview Serialization Module yaml

NimYAML

Introduction

NimYAML is a pure YAML implementation for Nim. It is able to read from and write to YAML character streams, and to serialize from and construct to native Nim types. It exclusively supports YAML 1.2.

Quickstart

Data used in quickstart code may not be accurate and is solely used to showcase NimYAML's features.

import yaml
type
    GenderKind* = enum
        male, female, other
    
    Person* = object
        name*: string
        gender*: GenderKind
        age*: int32
        spouse*: ref Person
        offspring*: seq[ref Person]

let input = newStringStream("""
%YAML 1.2
---
- &a
  name: Luke Skywalker
  gender: male
  age: 19
  spouse: ~
  offspring: []
- &b
  name: Han Solo
  gender: male
  age: 35
  spouse: &c
    name: Leia Organa
    gender: female
    age: 19
    spouse: *b
    offspring: []
  offspring: []
- *c
-
  name: Anakin Skywalker
  gender: male
  age: 42
  spouse: ~
  offspring: [*a, *c]
""")
var persons: seq[ref Person]
load(input, persons)
for person in persons:
  echo person.name, "\nage ", person.age
  if person.spouse != nil:
    echo "spouse: ", person.spouse.name
  for child in person.offspring:
    case child.gender
    of male: echo "son: ", child.name
    of female: echo "daughter: ", child.name
    of other: echo "child: ", child.name
  echo "------------------------"
dump(persons, newFileStream(stdout))