You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

131 lines
2.5 KiB

  1. # YAML support for the Go language
  2. Introduction
  3. ------------
  4. The yaml package enables Go programs to comfortably encode and decode YAML
  5. values. It was developed within [Canonical](https://www.canonical.com) as
  6. part of the [juju](https://juju.ubuntu.com) project, and is based on a
  7. pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML)
  8. C library to parse and generate YAML data quickly and reliably.
  9. Compatibility
  10. -------------
  11. The yaml package supports most of YAML 1.1 and 1.2, including support for
  12. anchors, tags, map merging, etc. Multi-document unmarshalling is not yet
  13. implemented, and base-60 floats from YAML 1.1 are purposefully not
  14. supported since they're a poor design and are gone in YAML 1.2.
  15. Installation and usage
  16. ----------------------
  17. The import path for the package is *gopkg.in/yaml.v2*.
  18. To install it, run:
  19. go get gopkg.in/yaml.v2
  20. API documentation
  21. -----------------
  22. If opened in a browser, the import path itself leads to the API documentation:
  23. * [https://gopkg.in/yaml.v2](https://gopkg.in/yaml.v2)
  24. API stability
  25. -------------
  26. The package API for yaml v2 will remain stable as described in [gopkg.in](https://gopkg.in).
  27. License
  28. -------
  29. The yaml package is licensed under the Apache License 2.0. Please see the LICENSE file for details.
  30. Example
  31. -------
  32. ```Go
  33. package main
  34. import (
  35. "fmt"
  36. "log"
  37. "gopkg.in/yaml.v2"
  38. )
  39. var data = `
  40. a: Easy!
  41. b:
  42. c: 2
  43. d: [3, 4]
  44. `
  45. type T struct {
  46. A string
  47. B struct {
  48. RenamedC int `yaml:"c"`
  49. D []int `yaml:",flow"`
  50. }
  51. }
  52. func main() {
  53. t := T{}
  54. err := yaml.Unmarshal([]byte(data), &t)
  55. if err != nil {
  56. log.Fatalf("error: %v", err)
  57. }
  58. fmt.Printf("--- t:\n%v\n\n", t)
  59. d, err := yaml.Marshal(&t)
  60. if err != nil {
  61. log.Fatalf("error: %v", err)
  62. }
  63. fmt.Printf("--- t dump:\n%s\n\n", string(d))
  64. m := make(map[interface{}]interface{})
  65. err = yaml.Unmarshal([]byte(data), &m)
  66. if err != nil {
  67. log.Fatalf("error: %v", err)
  68. }
  69. fmt.Printf("--- m:\n%v\n\n", m)
  70. d, err = yaml.Marshal(&m)
  71. if err != nil {
  72. log.Fatalf("error: %v", err)
  73. }
  74. fmt.Printf("--- m dump:\n%s\n\n", string(d))
  75. }
  76. ```
  77. This example will generate the following output:
  78. ```
  79. --- t:
  80. {Easy! {2 [3 4]}}
  81. --- t dump:
  82. a: Easy!
  83. b:
  84. c: 2
  85. d: [3, 4]
  86. --- m:
  87. map[a:Easy! b:map[c:2 d:[3 4]]]
  88. --- m dump:
  89. a: Easy!
  90. b:
  91. c: 2
  92. d:
  93. - 3
  94. - 4
  95. ```