Created
January 27, 2014 13:27
-
-
Save emicklei/8648546 to your computer and use it in GitHub Desktop.
jsonfmt
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" | |
"io/ioutil" | |
"log" | |
"os" | |
) | |
// reads array or hash, writes pretty JSON | |
func main() { | |
data, err := ioutil.ReadAll(os.Stdin) | |
if err != nil { | |
log.Fatal(err.Error()) | |
} | |
// try array | |
var array []map[string]interface{} | |
err = json.Unmarshal(data, &array) | |
if err != nil { | |
// try hash | |
var hash map[string]interface{} | |
err = json.Unmarshal(data, &hash) | |
if err != nil { | |
log.Fatalf("not a valid array|hash :%v", err) | |
} | |
// dump hash | |
out, err := json.MarshalIndent(hash, "", "\t") | |
if err != nil { | |
log.Fatal("error:", err) | |
} | |
os.Stdout.Write(out) | |
} else { | |
// dump array | |
out, err := json.MarshalIndent(array, "", "\t") | |
if err != nil { | |
log.Fatal("error:", err) | |
} | |
os.Stdout.Write(out) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment