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

Mary-Kate Olsen
Release: 2024-11-19 04:13:03
Original
246 people have browsed it

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))
}
Copy after login

Output:

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

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())
}
Copy after login

Output:

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

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)
}
Copy after login

Output:

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

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!

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