Home > Article > Backend Development > Does Go\'s `encoding/json` Package Offer a Way to Format JSON Output for Human Readability?
Question:
Is there an open-source Jq wrapper for Go that can convert machine-readable JSON output to human-readable format?
Answer:
Yes, the encoding/json package in Go provides built-in support for formatting JSON output.
Solution:
The following code demonstrates how to use json.MarshalIndent() to create indented JSON output:
import ( "encoding/json" "fmt" ) 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)) }
Output:
{ "id": "uuid1", "name": "John Smith" }
If you have an existing JSON string, you can use json.Indent() to format it:
import "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()) }
Output:
{ "id": "uuid1", "name": "John Smith" }
Customization:
You can customize the indentation using the prefix and indent parameters of the indent functions. For example:
data, err := json.MarshalIndent(m, "+", "-") if err != nil { panic(err) }
Output:
{ +--"id": "uuid1", +--"name": "John Smith" +}
The above is the detailed content of Does Go\'s `encoding/json` Package Offer a Way to Format JSON Output for Human Readability?. For more information, please follow other related articles on the PHP Chinese website!