Home > Article > Backend Development > How Can Go\'s `encoding/json` Package Generate Human-Readable JSON Output?
Using Go's Encoding/JSON Package for Human-Readable JSON Output
You mention facing the challenge of producing human-readable JSON output when piping the results of your foo command through jq. While there are no known open-source jq wrappers specifically designed for this purpose, you can leverage Go's built-in encoding/json package to achieve the desired outcome.
Utilizing json.MarshalIndent() and Encoder.SetIndent()
The json.MarshalIndent() function provides a convenient way to encode a JSON value as a formatted string. By specifying the desired prefix and indentation, you can produce human-readable output. Similarly, json.Encoder's SetIndent() method allows you to establish indentation for your JSON output.
Example Code
Here's an example that demonstrates the usage of json.MarshalIndent():
package main import ( "encoding/json" ) func main() { m := map[string]interface{}{"id": "uuid1", "name": "John Smith"} data, err := json.MarshalIndent(m, "", " ") if err != nil { panic(err) } fmt.Println(string(data)) }
You can also use json.NewEncoder to control indentation:
package main import ( "encoding/json" "os" ) func main() { enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") m := map[string]interface{}{"id": "uuid1", "name": "John Smith"} if err := enc.Encode(m); err != nil { panic(err) } }
Formatting Pre-Generated JSON Text
If you have pre-generated JSON text, you can utilize the json.Indent() function to format it:
package main import ( "bytes" "encoding/json" ) func main() { src := `{"id":"uuid1","name":"John Smith"}` dst := &bytes.Buffer{} if err := json.Indent(dst, []byte(src), "", " "); err != nil { panic(err) } fmt.Println(dst.String()) }
By using these techniques, you can easily produce human-readable JSON output within your Go programs without the need for external jq wrappers.
The above is the detailed content of How Can Go\'s `encoding/json` Package Generate Human-Readable JSON Output?. For more information, please follow other related articles on the PHP Chinese website!