Created
March 20, 2024 10:29
-
-
Save RussellJapheth/5c317783490afb83583bcc67c7572cac to your computer and use it in GitHub Desktop.
A terminal utility for formatting JSON files written in Go
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
// 1. Get the path for our input file from | |
// the command line arguments | |
// 2. Check if the input file is readable and contains | |
// valid JSON | |
// 3. Format the contents of the file | |
// 4. Save formatted JSON to another file | |
// 5. Compile our binary | |
package main | |
import ( | |
"bytes" | |
"encoding/json" | |
"errors" | |
"fmt" | |
"os" | |
) | |
// A function to check if a string is valid JSON | |
// src: https://stackoverflow.com/a/22129435 (modified) | |
func isJSON(s string) bool { | |
var js map[string]interface{} | |
return json.Unmarshal([]byte(s), &js) == nil | |
} | |
func FileExists(name string) (bool, error) { | |
_, err := os.Stat(name) | |
if err == nil { | |
return true, nil | |
} | |
if errors.Is(err, os.ErrNotExist) { | |
return false, nil | |
} | |
return false, err | |
} | |
// A function to pretty print JSON strings | |
// src: https://stackoverflow.com/a/36544455 | |
func jsonPrettyPrint(in string) string { | |
var out bytes.Buffer | |
err := json.Indent(&out, []byte(in), "", "\t") | |
if err != nil { | |
return in | |
} | |
return out.String() | |
} | |
func main() { | |
// Get the arguments passed to our program | |
arguments := os.Args[1:] | |
// Check that at least 1 argument was passed | |
if len(arguments) < 1 { | |
// Display error message and exit the program | |
fmt.Println("Missing required argument") | |
fmt.Println("Usage: ./prettyJson input_file.json") | |
return | |
} | |
// Call FileExists function with the file path | |
exists, err := FileExists(arguments[0]) | |
// Check the result | |
if exists != true { | |
fmt.Println("Sorry the file", arguments[0], "does not exist!") | |
return | |
} | |
if err != nil { | |
fmt.Println("Error:", err) | |
return | |
} | |
raw, err := os.ReadFile(arguments[0]) // just pass the file name | |
if err != nil { | |
fmt.Print(err) | |
} | |
// convert the files contents to string | |
contents := string(raw) | |
// check if the string is valid json | |
if contents == "" || isJSON(contents) != true { | |
fmt.Println("Invalid or empty JSON file") | |
return | |
} | |
// print the formatted string; this output can be piped to an output file | |
// no prefix and indenting with 4 spaces | |
formatted := jsonPrettyPrint(contents) | |
// Display the formatted string | |
fmt.Println(formatted) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment