This is a simple command-line tool built in Go that reads a messy or minified JSON or YAML file and prints a clean, pretty, and colorized version to the terminal.
It automatically detects the file type (.json, .yml, or .yaml) and formats it accordingly.
- Formats both JSON and YAML files.
- Automatically detects the file type based on its extension.
- Pretty-prints the output with standard indentation.
- Colorizes the output for better readability:
- Cyan for JSON
- Magenta for YAML
- Validates the file content and reports errors for invalid formats.
- Go (Version 1.18 or newer)
-
In your project directory, initialize the Go module:
go mod init go-formatter
-
Install the required dependencies:
go get gopkg.in/yaml.v3 go get github.com/fatih/color
Use go run . followed by the name of the file you want to format.
-
Create a file
messy.json:{"name":"John","age":30,"isStudent":false,"courses":[{"title":"History","credits":3}],"address":null} -
Run the tool:
go run . messy.json -
Output (in Cyan):
{ "address": null, "age": 30, "courses": [ { "credits": 3, "title": "History" } ], "isStudent": false, "name": "John" }
-
Create a file
messy.yaml:name: Jane age: 28 isStudent: true courses: - title: Math credits: 4 - title: Physics credits: 5 address: street: 123 Main St city: Anytown
-
Run the tool:
go run . messy.yaml -
Output (in Magenta):
name: Jane age: 28 isStudent: true courses: - title: Math credits: 4 - title: Physics credits: 5 address: street: 123 Main St city: Anytown
To use this like a real command-line tool without typing go run every time, you can build the binary:
# This creates an executable file (e.g., 'format' or 'format.exe')
go build -o formatNow you can run it directly from that folder:
./format messy.jsonos.Args: Used to read command-line arguments (specifically, the filename provided by the user).os.ReadFile: Reads the raw byte content of the specified file.filepath.Ext: Used to detect the file type by checking its extension.json.Unmarshal/yaml.Unmarshal: Parses the raw bytes into a genericinterface{}, which can hold any data structure.json.MarshalIndent/yaml.Marshal: Re-serializes theinterface{}back into a "pretty" byte slice.json.MarshalIndentis used to add indentation, while theyaml.v3library formats nicely by default.github.com/fatih/color: A third-party library used to wrap the output string in ANSI color codes for a better terminal experience.