yaml.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. package yaml
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "reflect"
  8. "strconv"
  9. "gopkg.in/yaml.v2"
  10. )
  11. // Marshals the object into JSON then converts JSON to YAML and returns the
  12. // YAML.
  13. func Marshal(o interface{}) ([]byte, error) {
  14. j, err := json.Marshal(o)
  15. if err != nil {
  16. return nil, fmt.Errorf("error marshaling into JSON: %v", err)
  17. }
  18. y, err := JSONToYAML(j)
  19. if err != nil {
  20. return nil, fmt.Errorf("error converting JSON to YAML: %v", err)
  21. }
  22. return y, nil
  23. }
  24. // JSONOpt is a decoding option for decoding from JSON format.
  25. type JSONOpt func(*json.Decoder) *json.Decoder
  26. // Unmarshal converts YAML to JSON then uses JSON to unmarshal into an object,
  27. // optionally configuring the behavior of the JSON unmarshal.
  28. func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error {
  29. vo := reflect.ValueOf(o)
  30. j, err := yamlToJSON(y, &vo, yaml.Unmarshal)
  31. if err != nil {
  32. return fmt.Errorf("error converting YAML to JSON: %v", err)
  33. }
  34. err = jsonUnmarshal(bytes.NewReader(j), o, opts...)
  35. if err != nil {
  36. return fmt.Errorf("error unmarshaling JSON: %v", err)
  37. }
  38. return nil
  39. }
  40. // jsonUnmarshal unmarshals the JSON byte stream from the given reader into the
  41. // object, optionally applying decoder options prior to decoding. We are not
  42. // using json.Unmarshal directly as we want the chance to pass in non-default
  43. // options.
  44. func jsonUnmarshal(r io.Reader, o interface{}, opts ...JSONOpt) error {
  45. d := json.NewDecoder(r)
  46. for _, opt := range opts {
  47. d = opt(d)
  48. }
  49. if err := d.Decode(&o); err != nil {
  50. return fmt.Errorf("while decoding JSON: %v", err)
  51. }
  52. return nil
  53. }
  54. // Convert JSON to YAML.
  55. func JSONToYAML(j []byte) ([]byte, error) {
  56. // Convert the JSON to an object.
  57. var jsonObj interface{}
  58. // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the
  59. // Go JSON library doesn't try to pick the right number type (int, float,
  60. // etc.) when unmarshalling to interface{}, it just picks float64
  61. // universally. go-yaml does go through the effort of picking the right
  62. // number type, so we can preserve number type throughout this process.
  63. err := yaml.Unmarshal(j, &jsonObj)
  64. if err != nil {
  65. return nil, err
  66. }
  67. // Marshal this object into YAML.
  68. return yaml.Marshal(jsonObj)
  69. }
  70. // YAMLToJSON converts YAML to JSON. Since JSON is a subset of YAML,
  71. // passing JSON through this method should be a no-op.
  72. //
  73. // Things YAML can do that are not supported by JSON:
  74. // * In YAML you can have binary and null keys in your maps. These are invalid
  75. // in JSON. (int and float keys are converted to strings.)
  76. // * Binary data in YAML with the !!binary tag is not supported. If you want to
  77. // use binary data with this library, encode the data as base64 as usual but do
  78. // not use the !!binary tag in your YAML. This will ensure the original base64
  79. // encoded data makes it all the way through to the JSON.
  80. //
  81. // For strict decoding of YAML, use YAMLToJSONStrict.
  82. func YAMLToJSON(y []byte) ([]byte, error) {
  83. return yamlToJSON(y, nil, yaml.Unmarshal)
  84. }
  85. // YAMLToJSONStrict is like YAMLToJSON but enables strict YAML decoding,
  86. // returning an error on any duplicate field names.
  87. func YAMLToJSONStrict(y []byte) ([]byte, error) {
  88. return yamlToJSON(y, nil, yaml.UnmarshalStrict)
  89. }
  90. func yamlToJSON(y []byte, jsonTarget *reflect.Value, yamlUnmarshal func([]byte, interface{}) error) ([]byte, error) {
  91. // Convert the YAML to an object.
  92. var yamlObj interface{}
  93. err := yamlUnmarshal(y, &yamlObj)
  94. if err != nil {
  95. return nil, err
  96. }
  97. // YAML objects are not completely compatible with JSON objects (e.g. you
  98. // can have non-string keys in YAML). So, convert the YAML-compatible object
  99. // to a JSON-compatible object, failing with an error if irrecoverable
  100. // incompatibilties happen along the way.
  101. jsonObj, err := convertToJSONableObject(yamlObj, jsonTarget)
  102. if err != nil {
  103. return nil, err
  104. }
  105. // Convert this object to JSON and return the data.
  106. return json.Marshal(jsonObj)
  107. }
  108. func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (interface{}, error) {
  109. var err error
  110. // Resolve jsonTarget to a concrete value (i.e. not a pointer or an
  111. // interface). We pass decodingNull as false because we're not actually
  112. // decoding into the value, we're just checking if the ultimate target is a
  113. // string.
  114. if jsonTarget != nil {
  115. ju, tu, pv := indirect(*jsonTarget, false)
  116. // We have a JSON or Text Umarshaler at this level, so we can't be trying
  117. // to decode into a string.
  118. if ju != nil || tu != nil {
  119. jsonTarget = nil
  120. } else {
  121. jsonTarget = &pv
  122. }
  123. }
  124. // If yamlObj is a number or a boolean, check if jsonTarget is a string -
  125. // if so, coerce. Else return normal.
  126. // If yamlObj is a map or array, find the field that each key is
  127. // unmarshaling to, and when you recurse pass the reflect.Value for that
  128. // field back into this function.
  129. switch typedYAMLObj := yamlObj.(type) {
  130. case map[interface{}]interface{}:
  131. // JSON does not support arbitrary keys in a map, so we must convert
  132. // these keys to strings.
  133. //
  134. // From my reading of go-yaml v2 (specifically the resolve function),
  135. // keys can only have the types string, int, int64, float64, binary
  136. // (unsupported), or null (unsupported).
  137. strMap := make(map[string]interface{})
  138. for k, v := range typedYAMLObj {
  139. // Resolve the key to a string first.
  140. var keyString string
  141. switch typedKey := k.(type) {
  142. case string:
  143. keyString = typedKey
  144. case int:
  145. keyString = strconv.Itoa(typedKey)
  146. case int64:
  147. // go-yaml will only return an int64 as a key if the system
  148. // architecture is 32-bit and the key's value is between 32-bit
  149. // and 64-bit. Otherwise the key type will simply be int.
  150. keyString = strconv.FormatInt(typedKey, 10)
  151. case float64:
  152. // Stolen from go-yaml to use the same conversion to string as
  153. // the go-yaml library uses to convert float to string when
  154. // Marshaling.
  155. s := strconv.FormatFloat(typedKey, 'g', -1, 32)
  156. switch s {
  157. case "+Inf":
  158. s = ".inf"
  159. case "-Inf":
  160. s = "-.inf"
  161. case "NaN":
  162. s = ".nan"
  163. }
  164. keyString = s
  165. case bool:
  166. if typedKey {
  167. keyString = "true"
  168. } else {
  169. keyString = "false"
  170. }
  171. default:
  172. return nil, fmt.Errorf("Unsupported map key of type: %s, key: %+#v, value: %+#v",
  173. reflect.TypeOf(k), k, v)
  174. }
  175. // jsonTarget should be a struct or a map. If it's a struct, find
  176. // the field it's going to map to and pass its reflect.Value. If
  177. // it's a map, find the element type of the map and pass the
  178. // reflect.Value created from that type. If it's neither, just pass
  179. // nil - JSON conversion will error for us if it's a real issue.
  180. if jsonTarget != nil {
  181. t := *jsonTarget
  182. if t.Kind() == reflect.Struct {
  183. keyBytes := []byte(keyString)
  184. // Find the field that the JSON library would use.
  185. var f *field
  186. fields := cachedTypeFields(t.Type())
  187. for i := range fields {
  188. ff := &fields[i]
  189. if bytes.Equal(ff.nameBytes, keyBytes) {
  190. f = ff
  191. break
  192. }
  193. // Do case-insensitive comparison.
  194. if f == nil && ff.equalFold(ff.nameBytes, keyBytes) {
  195. f = ff
  196. }
  197. }
  198. if f != nil {
  199. // Find the reflect.Value of the most preferential
  200. // struct field.
  201. jtf := t.Field(f.index[0])
  202. strMap[keyString], err = convertToJSONableObject(v, &jtf)
  203. if err != nil {
  204. return nil, err
  205. }
  206. continue
  207. }
  208. } else if t.Kind() == reflect.Map {
  209. // Create a zero value of the map's element type to use as
  210. // the JSON target.
  211. jtv := reflect.Zero(t.Type().Elem())
  212. strMap[keyString], err = convertToJSONableObject(v, &jtv)
  213. if err != nil {
  214. return nil, err
  215. }
  216. continue
  217. }
  218. }
  219. strMap[keyString], err = convertToJSONableObject(v, nil)
  220. if err != nil {
  221. return nil, err
  222. }
  223. }
  224. return strMap, nil
  225. case []interface{}:
  226. // We need to recurse into arrays in case there are any
  227. // map[interface{}]interface{}'s inside and to convert any
  228. // numbers to strings.
  229. // If jsonTarget is a slice (which it really should be), find the
  230. // thing it's going to map to. If it's not a slice, just pass nil
  231. // - JSON conversion will error for us if it's a real issue.
  232. var jsonSliceElemValue *reflect.Value
  233. if jsonTarget != nil {
  234. t := *jsonTarget
  235. if t.Kind() == reflect.Slice {
  236. // By default slices point to nil, but we need a reflect.Value
  237. // pointing to a value of the slice type, so we create one here.
  238. ev := reflect.Indirect(reflect.New(t.Type().Elem()))
  239. jsonSliceElemValue = &ev
  240. }
  241. }
  242. // Make and use a new array.
  243. arr := make([]interface{}, len(typedYAMLObj))
  244. for i, v := range typedYAMLObj {
  245. arr[i], err = convertToJSONableObject(v, jsonSliceElemValue)
  246. if err != nil {
  247. return nil, err
  248. }
  249. }
  250. return arr, nil
  251. default:
  252. // If the target type is a string and the YAML type is a number,
  253. // convert the YAML type to a string.
  254. if jsonTarget != nil && (*jsonTarget).Kind() == reflect.String {
  255. // Based on my reading of go-yaml, it may return int, int64,
  256. // float64, or uint64.
  257. var s string
  258. switch typedVal := typedYAMLObj.(type) {
  259. case int:
  260. s = strconv.FormatInt(int64(typedVal), 10)
  261. case int64:
  262. s = strconv.FormatInt(typedVal, 10)
  263. case float64:
  264. s = strconv.FormatFloat(typedVal, 'g', -1, 32)
  265. case uint64:
  266. s = strconv.FormatUint(typedVal, 10)
  267. case bool:
  268. if typedVal {
  269. s = "true"
  270. } else {
  271. s = "false"
  272. }
  273. }
  274. if len(s) > 0 {
  275. yamlObj = interface{}(s)
  276. }
  277. }
  278. return yamlObj, nil
  279. }
  280. return nil, nil
  281. }