Last active
August 29, 2015 13:58
-
-
Save miquella/9983898 to your computer and use it in GitHub Desktop.
JSON Formatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"os" | |
"strings" | |
"text/template" | |
) | |
func main() { | |
data, err := ioutil.ReadAll(os.Stdin) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "reading stdin failed: %s", err) | |
os.Exit(1) | |
} | |
v := make(map[string]interface{}) | |
err = json.Unmarshal(data, &v) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "invalid json: %s", err) | |
os.Exit(2) | |
} | |
if len(os.Args) < 2 { | |
out, err := json.MarshalIndent(v, "", " ") | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "failed to write json: %s", err) | |
os.Exit(3) | |
} | |
fmt.Fprint(os.Stdout, string(out)) | |
} else { | |
delimiter := "" | |
for _, arg := range os.Args[1:] { | |
fmt.Fprint(os.Stdout, delimiter) | |
t := template.New("Arg") | |
if strings.Contains(arg, "{{") { | |
_, err = t.Parse(arg) | |
} else { | |
_, err = t.Parse(fmt.Sprintf("{{.%s}}", arg)) | |
} | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "cannot parse template field: %s", err) | |
continue | |
} | |
err = t.Execute(os.Stdout, v) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "failed to execute template: %s", err) | |
os.Exit(3) | |
} | |
delimiter = "\n" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment