Home > Backend Development > Golang > How to Pretty Print JSON Output in Go Using Built-in Functions?

How to Pretty Print JSON Output in Go Using Built-in Functions?

Linda Hamilton
Release: 2024-11-22 04:54:11
Original
638 people have browsed it

How to Pretty Print JSON Output in Go Using Built-in Functions?

Pretty Printing JSON Output in Go with Built-in Functions

When dealing with JSON output in Go programs, it's often desirable to make it human readable. While jq can be used for this purpose, there are also built-in functions within the Go standard library that can achieve the desired result.

Json Marshal Indenting

The encoding/json package provides the json.MarshalIndent() function for pretty printing JSON output. It takes two additional parameters:

  • prefix: The string to add before each line
  • indent: The string to add after each level of indentation

By passing an empty string as the prefix and a space as the indent, you can obtain human readable JSON output:

m := map[string]interface{}{"id": "uuid1", "name": "John Smith"}

data, err := json.MarshalIndent(m, "", "  ")
if err != nil {
    panic(err)
}
fmt.Println(string(data))
Copy after login

Output:

{
  "id": "uuid1",
  "name": "John Smith"
}
{
  "id": "uuid1",
  "name": "John Smith"
}
Copy after login

You can also use the json.Encoder.SetIndent() method to set the indentation parameters when using an Encoder:

enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", "  ")
if err := enc.Encode(m); err != nil {
    panic(err)
}
Copy after login

Json Indenting

If you already have a JSON string, you can use the json.Indent() function to format it:

src := `{"id":"uuid1","name":"John Smith"}`

dst := &bytes.Buffer{}
if err := json.Indent(dst, []byte(src), "", "  "); err != nil {
    panic(err)
}
fmt.Println(dst.String())
Copy after login

Output:

{
  "id": "uuid1",
  "name": "John Smith"
}
Copy after login

The above is the detailed content of How to Pretty Print JSON Output in Go Using Built-in Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template