-
-
Notifications
You must be signed in to change notification settings - Fork 564
/
Copy pathmarshal.go
52 lines (48 loc) Β· 1.29 KB
/
marshal.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
package openapi
import (
"encoding/json"
"gopkg.in/yaml.v2"
)
// MarshalJSON produces the JSON resulting from encoding an object composed of
// the fields in v (which must me a struct) and the keys in extensions.
func MarshalJSON(v interface{}, extensions map[string]interface{}) ([]byte, error) {
marshaled, err := json.Marshal(v)
if err != nil {
return nil, err
}
if len(extensions) == 0 {
return marshaled, nil
}
var unmarshaled interface{}
if err := json.Unmarshal(marshaled, &unmarshaled); err != nil {
return nil, err
}
asserted := unmarshaled.(map[string]interface{})
for k, v := range extensions {
asserted[k] = v
}
merged, err := json.Marshal(asserted)
if err != nil {
return nil, err
}
return merged, nil
}
// MarshalYAML produces the JSON resulting from encoding an object composed of
// the fields in v (which must me a struct) and the keys in extensions.
func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {
if len(extensions) == 0 {
return v, nil
}
marshaled, err := yaml.Marshal(v)
if err != nil {
return nil, err
}
var unmarshaled map[string]interface{}
if err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {
return nil, err
}
for k, v := range extensions {
unmarshaled[k] = v
}
return unmarshaled, nil
}