我正在嘗試學習Golang,在這樣做的同時,我寫了下面的代碼(更大的自學項目的一部分),并從陌生人那里進行了代碼審查,其中一條評論是,“你可以直接將其編組到stdout,而不是編組到堆,然后轉換為字符串,然后將其流式傳輸到stdout"我已經瀏覽了編碼/ json包和io的文檔,但無法拼湊出所需的更改。任何指示或幫助都會很棒。 // Marshal the struct with proper tab indent so it can be readable b, err := json.MarshalIndent(res, "", " ") if err != nil { log.Fatal(errors.Wrap(err, "error marshaling response data")) } // Print the output to the stdout fmt.Fprint(os.Stdout, string(b))編輯我剛剛在文檔中找到了下面的代碼示例: var out bytes.Buffer json.Indent(&out, b, "=", "\t") out.WriteTo(os.Stdout)但是,它再次寫入堆,然后再寫入 。不過,它確實刪除了將其轉換為字符串的一個步驟。stdout
1 回答

HUX布斯
TA貢獻1876條經驗 獲得超6個贊
創建并使用 json。編碼器
定向到 os。司徒
。斷續器。新編碼器()
接受任何 io。作家
作為其目的地。
res := map[string]interface{}{
"one": 1,
"two": "twotwo",
}
if err := json.NewEncoder(os.Stdout).Encode(res); err != nil {
panic(err)
}
這將輸出(直接輸出到標準輸出):
{"one":1,"two":"twotwo"}
如果要設置縮進,請使用其編碼器.
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if err := enc.Encode(res); err != nil {
panic(err)
}
這將輸出:
{
"one": 1,
"two": "twotwo"
}
- 1 回答
- 0 關注
- 86 瀏覽
添加回答
舉報
0/150
提交
取消