Home  >  Article  >  Backend Development  >  Does Go\'s `encoding/json` Package Offer a Way to Format JSON Output for Human Readability?

Does Go\'s `encoding/json` Package Offer a Way to Format JSON Output for Human Readability?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-19 04:13:03246browse

Does Go's `encoding/json` Package Offer a Way to Format JSON Output for Human Readability?

Jq Wrapper for Human-Readable JSON Output in Go

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!

Statement:
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