yq/json_converter.go

70 lines
1.6 KiB
Go
Raw Normal View History

2015-10-10 23:00:22 +00:00
package main
import (
"encoding/json"
2017-02-26 22:01:52 +00:00
"github.com/mikefarah/yaml/Godeps/_workspace/src/gopkg.in/yaml.v2"
2015-10-10 23:00:22 +00:00
)
2015-10-11 06:06:52 +00:00
func fromJSONBytes(jsonBytes []byte, parsedData *map[interface{}]interface{}) {
*parsedData = make(map[interface{}]interface{})
var jsonData map[string]interface{}
err := json.Unmarshal(jsonBytes, &jsonData)
if err != nil {
die("error parsing data: ", err)
}
for key, value := range jsonData {
(*parsedData)[key] = fromJSON(value)
}
}
2015-10-10 23:00:22 +00:00
func jsonToString(context interface{}) string {
out, err := json.Marshal(toJSON(context))
if err != nil {
die("error printing yaml as json: ", err)
}
return string(out)
}
2015-10-11 06:06:52 +00:00
func fromJSON(context interface{}) interface{} {
switch context.(type) {
case []interface{}:
oldArray := context.([]interface{})
newArray := make([]interface{}, len(oldArray))
for index, value := range oldArray {
newArray[index] = fromJSON(value)
}
return newArray
case map[string]interface{}:
oldMap := context.(map[string]interface{})
newMap := make(map[interface{}]interface{})
for key, value := range oldMap {
newMap[key] = fromJSON(value)
}
return newMap
default:
return context
}
}
2015-10-10 23:00:22 +00:00
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
2017-02-26 22:01:52 +00:00
case yaml.MapSlice:
oldMap := context.(yaml.MapSlice)
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 {
newMap[entry.Key.(string)] = toJSON(entry.Value)
2015-10-10 23:00:22 +00:00
}
return newMap
default:
return context
}
}