package main import ( "bytes" "encoding/json" "fmt" "io" "os" "testing" ) // PrettyJSON formats compact or minified JSON using the requested indentation. func PrettyJSON(src []byte, indent string) ([]byte, error) { var out bytes.Buffer if err := json.Indent(&out, bytes.TrimSpace(src), "", indent); err != nil { return nil, err } out.WriteByte('\n') return out.Bytes(), nil } func main() { in, err := io.ReadAll(os.Stdin) if err != nil { fmt.Fprintln(os.Stderr, "read stdin:", err) os.Exit(1) } out, err := PrettyJSON(in, " ") if err != nil { fmt.Fprintln(os.Stderr, "invalid json:", err) os.Exit(1) } if _, err := os.Stdout.Write(out); err != nil { fmt.Fprintln(os.Stderr, "write stdout:", err) os.Exit(1) } } func TestPrettyJSONObject(t *testing.T) { got, err := PrettyJSON([]byte(`{"name":"Ada","skills":["math","code"]}`), " ") if err != nil { t.Fatal(err) } want := "{\n \"name\": \"Ada\",\n \"skills\": [\n \"math\",\n \"code\"\n ]\n}\n" if string(got) != want { t.Fatalf("PrettyJSON() = %q, want %q", got, want) } } func TestPrettyRejectsInvalidJSON(t *testing.T) { if _, err := PrettyJSON([]byte(`{"missing":]`), " "); err == nil { t.Fatal("PrettyJSON() error = nil, want non-nil") } }