yq/json_converter.go
kenjones 3beee3f804 Bugfix: Panic on non-string keys
Adds check if the key is an `int` or `bool`, and converts to a string
as part of the `toJSON` function.
Test cases added.

Resolves: #28
2017-09-21 12:01:03 -04:00

44 lines
997 B
Go

package main
import (
"encoding/json"
"strconv"
yaml "gopkg.in/yaml.v2"
)
func jsonToString(context interface{}) string {
out, err := json.Marshal(toJSON(context))
if err != nil {
die("error printing yaml as json: ", err)
}
return string(out)
}
func toJSON(context interface{}) interface{} {
switch context.(type) {
case []interface{}:
oldArray := context.([]interface{})
newArray := make([]interface{}, len(oldArray))
for index, value := range oldArray {
newArray[index] = toJSON(value)
}
return newArray
case yaml.MapSlice:
oldMap := context.(yaml.MapSlice)
newMap := make(map[string]interface{})
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)
}
}
return newMap
default:
return context
}
}