我如何美化json中的输出?

问题描述 投票:0回答:2

所以我写了这个非常简单的go应用,它所做的所有事情都显示了JSON信息,但是所有输出数据都已缩小,我需要一些帮助来美化所有数据。

package main

import (
    "encoding/json"
    "net/http"
)

func main() {
    http.HandleFunc("/", ExampleHandler)
    if err := http.ListenAndServe(":8080", nil); err != nil {
        panic(err)
    }
}

func ExampleHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Add("Content-Type", "application/json")
    resp, _ := json.Marshal(map[string]string{
        "accept":                    r.Header.Get("Accept"),
        "accept_encoding":           r.Header.Get("Accept-Encoding"),
        "accept_language":           r.Header.Get("Accept-Language"),
        "cache_control":             r.Header.Get("Cache-Control"),
        "dnt":                       r.Header.Get("DNT"),
        "ip":                        r.Header.Get("CF-CONNECTING-IP"),
        "referer":                   r.Header.Get("Referer"),
        "sec_fetch_dest":            r.Header.Get("Sec-Fetch-Dest"),
        "sec_fetch_mode":            r.Header.Get("Sec-Fetch-Mode"),
        "sec_fetch_user":            r.Header.Get("Sec-Fetch-User"),
        "sec_fetch_site":            r.Header.Get("Sec-Fetch-Site"),
        "upgrade_insecure_requests": r.Header.Get("Upgrade-Insecure-Requests"),
        "user_agent":                r.Header.Get("User-Agent"),
    })
    w.Write(resp)
}
arrays json go code-formatting golang-migrate
2个回答
1
投票

使用json.Indent

resp, _ := json.Marshal(...)
dst := bytes.Buffer{}
json.Indent(&dst,resp,"","  ")
w.Write(dsr.Bytes())

0
投票

更改

resp, _ := json.Marshal(map[string]string{...})

to

resp, _ := json.MarshalIndent(map[string]string{...}, "", " ")

请参见json.MarshalIndent()

© www.soinside.com 2019 - 2024. All rights reserved.