Added json output functionality

This commit is contained in:
Mike Farah 2015-10-11 10:00:22 +11:00
parent 5f09aabf4c
commit 3720bf8211
4 changed files with 73 additions and 4 deletions

View File

@ -160,3 +160,6 @@ b:
- name: Howdy Partner
```
## Convert to json
To convert output to json, use the --tojson (or -j) flag. This can be used with any command.

34
json_converter.go Normal file
View File

@ -0,0 +1,34 @@
package main
import (
"encoding/json"
)
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 map[interface{}]interface{}:
oldMap := context.(map[interface{}]interface{})
newMap := make(map[string]interface{})
for key, value := range oldMap {
newMap[key.(string)] = toJSON(value)
}
return newMap
default:
return context
}
}

24
json_converter_test.go Normal file
View File

@ -0,0 +1,24 @@
package main
import (
"testing"
)
func TestJsonToString(t *testing.T) {
var data = parseData(`
---
b:
c: 2
`)
assertResult(t, "{\"b\":{\"c\":2}}", jsonToString(data))
}
func TestJsonToString_withArray(t *testing.T) {
var data = parseData(`
---
b:
- item: one
- item: two
`)
assertResult(t, "{\"b\":[{\"item\":\"one\"},{\"item\":\"two\"}]}", jsonToString(data))
}

16
yaml.go
View File

@ -13,6 +13,7 @@ import (
var trimOutput = true
var writeInplace = false
var writeScript = ""
var outputToJSON = false
func main() {
var cmdRead = &cobra.Command{
@ -59,12 +60,13 @@ a.b.e:
var rootCmd = &cobra.Command{Use: "yaml"}
rootCmd.PersistentFlags().BoolVarP(&trimOutput, "trim", "t", true, "trim yaml output")
rootCmd.PersistentFlags().BoolVarP(&outputToJSON, "tojson", "j", false, "output as json")
rootCmd.AddCommand(cmdRead, cmdWrite)
rootCmd.Execute()
}
func readProperty(cmd *cobra.Command, args []string) {
printYaml(read(args))
print(read(args))
}
func read(args []string) interface{} {
@ -86,7 +88,7 @@ func writeProperty(cmd *cobra.Command, args []string) {
if writeInplace {
ioutil.WriteFile(args[0], []byte(yamlToString(updatedData)), 0644)
} else {
printYaml(updatedData)
print(updatedData)
}
}
@ -128,8 +130,14 @@ func parseValue(argument string) interface{} {
return argument[1 : len(argument)-1]
}
func printYaml(context interface{}) {
fmt.Println(yamlToString(context))
func print(context interface{}) {
var out string
if outputToJSON {
out = jsonToString(context)
} else {
out = yamlToString(context)
}
fmt.Println(out)
}
func yamlToString(context interface{}) string {