package main import ( "bytes" "encoding/json" "fmt" "io" "os" ) // prettyJSON formats JSON with two-space indentation. func prettyJSON(src []byte) ([]byte, error) { var out bytes.Buffer if err := json.Indent(&out, bytes.TrimSpace(src), "", " "); err != nil { return nil, err } out.WriteByte('\n') return out.Bytes(), nil } // runTests provides a couple of lightweight checks in this single-file program. func runTests() error { tests := []struct { input string want string }{ {`{"name":"Ada","active":true}`, "{\n \"name\": \"Ada\",\n \"active\": true\n}\n"}, {`[1,{"x":null}]`, "[\n 1,\n {\n \"x\": null\n }\n]\n"}, } for i, test := range tests { got, err := prettyJSON([]byte(test.input)) if err != nil { return fmt.Errorf("test %d: %w", i+1, err) } if string(got) != test.want { return fmt.Errorf("test %d: got %q, want %q", i+1, got, test.want) } } return nil } func main() { if len(os.Args) == 2 && os.Args[1] == "-test" { if err := runTests(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } fmt.Println("tests passed") return } input, err := io.ReadAll(os.Stdin) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } output, err := prettyJSON(input) if err != nil { fmt.Fprintln(os.Stderr, "invalid JSON:", err) os.Exit(1) } os.Stdout.Write(output) }