-
Notifications
You must be signed in to change notification settings - Fork 0
/
jaml.go
79 lines (64 loc) · 1.53 KB
/
jaml.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"gopkg.in/yaml.v2"
)
func unmarshaledDataToBytes(data interface{}) interface{} {
switch d := data.(type) {
case map[interface{}]interface{}:
m := map[string]interface{}{}
for k, v := range d {
m[k.(string)] = unmarshaledDataToBytes(v)
}
return m
case []interface{}:
for i, v := range d {
d[i] = unmarshaledDataToBytes(v)
}
}
return data
}
// JAML convert JSON to YAML or YAML to JSON.
func JAML(bytes []byte) ([]byte, error) {
var data interface{}
// JSON to YAML
if json.Valid(bytes) {
if err := json.Unmarshal(bytes, &data); err != nil {
return nil, fmt.Errorf("json.Unmarshal: %v", err)
}
b, err := yaml.Marshal(data)
if err != nil {
return nil, fmt.Errorf("yaml.Marshal: %v", err)
}
// add `---` to the first line.
b = append([]byte("---\n"), b...)
return b, nil
}
// YAML to JSON
if err := yaml.Unmarshal(bytes, &data); err != nil {
return nil, fmt.Errorf("yaml.Unmarshal: %v", err)
}
//b, err := json.MarshalIndent(unmarshaledDataToBytes(data), "", "\t")
b, err := json.Marshal(unmarshaledDataToBytes(data))
if err != nil {
return nil, fmt.Errorf("json.Marshal: %v", err)
}
// add `\n` to the last line.
b = append(b, []byte("\n")...)
return b, nil
}
func main() {
bytes, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatalf("[ERROR] Input data is wrong: %v", err)
}
bytes, err = JAML(bytes)
if err != nil {
log.Fatalf("[ERROR] Failed to convert input data: %v", err)
}
fmt.Printf("%s", bytes)
}