backend: add --json flag to always output JSON

This commit is contained in:
Nick Craig-Wood 2020-05-13 18:07:41 +01:00
parent 5eb558e058
commit 995cd0dc32

View File

@ -18,12 +18,14 @@ import (
var ( var (
options []string options []string
useJSON bool
) )
func init() { func init() {
cmd.Root.AddCommand(commandDefinition) cmd.Root.AddCommand(commandDefinition)
cmdFlags := commandDefinition.Flags() cmdFlags := commandDefinition.Flags()
flags.StringArrayVarP(cmdFlags, &options, "option", "o", options, "Option in the form name=value or name.") flags.StringArrayVarP(cmdFlags, &options, "option", "o", options, "Option in the form name=value or name.")
flags.BoolVarP(cmdFlags, &useJSON, "json", "", useJSON, "Always output in JSON format.")
} }
var commandDefinition = &cobra.Command{ var commandDefinition = &cobra.Command{
@ -97,6 +99,10 @@ Note to run these commands on a running backend then see
} }
// Output the result // Output the result
writeJSON := false
if useJSON {
writeJSON = true
} else {
switch x := out.(type) { switch x := out.(type) {
case nil: case nil:
case string: case string:
@ -106,6 +112,10 @@ Note to run these commands on a running backend then see
fmt.Println(line) fmt.Println(line)
} }
default: default:
writeJSON = true
}
}
if writeJSON {
// Write indented JSON to the output // Write indented JSON to the output
enc := json.NewEncoder(os.Stdout) enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", "\t") enc.SetIndent("", "\t")