2019-12-01 19:44:44 +00:00
|
|
|
package marshal
|
2015-10-10 23:00:22 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2017-09-22 19:58:12 +00:00
|
|
|
"fmt"
|
2017-09-21 16:01:03 +00:00
|
|
|
"strconv"
|
2017-09-20 23:40:33 +00:00
|
|
|
|
2019-09-03 05:52:55 +00:00
|
|
|
yaml "github.com/mikefarah/yaml/v2"
|
2015-10-10 23:00:22 +00:00
|
|
|
)
|
|
|
|
|
2019-12-01 19:44:44 +00:00
|
|
|
type JsonConverter interface {
|
|
|
|
JsonToString(context interface{}) (string, error)
|
|
|
|
}
|
|
|
|
|
2019-12-01 20:10:42 +00:00
|
|
|
type jsonConverter struct{}
|
2019-12-01 19:44:44 +00:00
|
|
|
|
|
|
|
func NewJsonConverter() JsonConverter {
|
|
|
|
return &jsonConverter{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (j *jsonConverter) JsonToString(context interface{}) (string, error) {
|
|
|
|
out, err := json.Marshal(j.toJSON(context))
|
2015-10-10 23:00:22 +00:00
|
|
|
if err != nil {
|
2017-09-22 19:58:12 +00:00
|
|
|
return "", fmt.Errorf("error printing yaml as json: %v", err)
|
2015-10-10 23:00:22 +00:00
|
|
|
}
|
2017-09-22 19:58:12 +00:00
|
|
|
return string(out), nil
|
2015-10-10 23:00:22 +00:00
|
|
|
}
|
|
|
|
|
2019-12-01 19:44:44 +00:00
|
|
|
func (j *jsonConverter) toJSON(context interface{}) interface{} {
|
2019-01-20 22:33:14 +00:00
|
|
|
switch context := context.(type) {
|
2015-10-10 23:00:22 +00:00
|
|
|
case []interface{}:
|
2019-01-20 22:33:14 +00:00
|
|
|
oldArray := context
|
2015-10-10 23:00:22 +00:00
|
|
|
newArray := make([]interface{}, len(oldArray))
|
|
|
|
for index, value := range oldArray {
|
2019-12-01 19:44:44 +00:00
|
|
|
newArray[index] = j.toJSON(value)
|
2015-10-10 23:00:22 +00:00
|
|
|
}
|
|
|
|
return newArray
|
2017-02-26 22:01:52 +00:00
|
|
|
case yaml.MapSlice:
|
2019-01-20 22:33:14 +00:00
|
|
|
oldMap := context
|
2015-10-10 23:00:22 +00:00
|
|
|
newMap := make(map[string]interface{})
|
2017-02-26 22:01:52 +00:00
|
|
|
for _, entry := range oldMap {
|
2017-09-21 16:01:03 +00:00
|
|
|
if str, ok := entry.Key.(string); ok {
|
2019-12-01 19:44:44 +00:00
|
|
|
newMap[str] = j.toJSON(entry.Value)
|
2017-09-21 16:01:03 +00:00
|
|
|
} else if i, ok := entry.Key.(int); ok {
|
2019-12-01 19:44:44 +00:00
|
|
|
newMap[strconv.Itoa(i)] = j.toJSON(entry.Value)
|
2017-09-21 16:01:03 +00:00
|
|
|
} else if b, ok := entry.Key.(bool); ok {
|
2019-12-01 19:44:44 +00:00
|
|
|
newMap[strconv.FormatBool(b)] = j.toJSON(entry.Value)
|
2017-09-21 16:01:03 +00:00
|
|
|
}
|
2015-10-10 23:00:22 +00:00
|
|
|
}
|
|
|
|
return newMap
|
|
|
|
default:
|
|
|
|
return context
|
|
|
|
}
|
|
|
|
}
|