Introduction
JSON (JavaScript Object Notation) is a popular format for data exchange due to its simplicity and readability. However, raw JSON can often be compact and hard to interpret. Formatting a JSON string to make it more readable is a common requirement for developers during debugging or data analysis. This program demonstrates how to use Go (Golang) to format a JSON string into a more human-readable structure with proper indentation.
Objective
The goal of this program is to take a compact JSON string as input, format it with indentation for better readability, and output the formatted JSON string. This program is intended for beginners and intermediate developers looking to understand JSON parsing and formatting in Go.
Code
package main import ( "bytes" "encoding/json" "fmt" "os" ) func main() { // Example compact JSON string compactJSON := `{"name":"John","age":30,"city":"New York","languages":["English","Spanish"]}` // Call the formatJSON function formattedJSON, err := formatJSON(compactJSON) if err != nil { fmt.Fprintf(os.Stderr, "Error formatting JSON: %v\n", err) os.Exit(1) } // Print the formatted JSON fmt.Println("Formatted JSON:") fmt.Println(formattedJSON) } // formatJSON takes a compact JSON string and returns a formatted version with indentation func formatJSON(input string) (string, error) { var buffer bytes.Buffer // Unmarshal the JSON into a generic interface var rawJSON interface{} err := json.Unmarshal([]byte(input), &rawJSON) if err != nil { return "", err } // Marshal the JSON with indentation into the buffer err = json.NewEncoder(&buffer).Encode(rawJSON) if err != nil { return "", err } return buffer.String(), nil }
Explanation
This program performs the following steps:
- Import necessary packages: The program uses the
encoding/json
package for JSON operations andbytes
for buffering the output. - Define a sample JSON string: A compact JSON string is used as an example input.
- Unmarshal the JSON: The compact JSON string is unmarshaled into a generic interface, allowing Go to understand its structure.
- Marshal with indentation: The unmarshaled JSON is then marshaled back into a formatted JSON string with indentation using a buffer.
- Handle errors: Errors during unmarshaling or marshaling are captured and displayed.
How to Run
- Install Go from the official Go website.
- Copy the code into a file named
format_json.go
. - Run the program using the command:
go run format_json.go
- Observe the formatted JSON output in the terminal.