yq/pkg/yqlib/json_converter.go

45 lines
1.0 KiB
Go
Raw Normal View History

package yqlib
2015-10-10 23:00:22 +00:00
import (
"encoding/json"
"fmt"
"strconv"
2019-09-03 05:52:55 +00:00
yaml "github.com/mikefarah/yaml/v2"
2015-10-10 23:00:22 +00:00
)
func JsonToString(context interface{}) (string, error) {
2015-10-10 23:00:22 +00:00
out, err := json.Marshal(toJSON(context))
if err != nil {
return "", fmt.Errorf("error printing yaml as json: %v", err)
2015-10-10 23:00:22 +00:00
}
return string(out), nil
2015-10-10 23:00:22 +00:00
}
func 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 {
newArray[index] = toJSON(value)
}
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 {
if str, ok := entry.Key.(string); ok {
newMap[str] = toJSON(entry.Value)
} else if i, ok := entry.Key.(int); ok {
newMap[strconv.Itoa(i)] = toJSON(entry.Value)
} else if b, ok := entry.Key.(bool); ok {
newMap[strconv.FormatBool(b)] = toJSON(entry.Value)
}
2015-10-10 23:00:22 +00:00
}
return newMap
default:
return context
}
}