我正在尝试学习 Golang,在这样做的同时,我写了下面的代码(更大的自学项目的一部分)并从陌生人那里接受了代码审查,其中一条评论是,“您可以将其直接编组到标准输出,而不是编组到堆,然后转换为字符串,然后将其流式传输到标准输出“
我已经阅读了encoding/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))
Run Code Online (Sandbox Code Playgroud)
编辑
我刚刚在文档中找到以下代码示例:
var out bytes.Buffer
json.Indent(&out, b, "=", "\t")
out.WriteTo(os.Stdout)
Run Code Online (Sandbox Code Playgroud)
但它再次写入堆,然后再写入stdout. 不过,它确实删除了将其转换为字符串的一个步骤。
创建和使用json.Encoder定向到os.Stdout. json.NewEncoder()接受 anyio.Writer作为其目的地。
res := map[string]interface{}{
"one": 1,
"two": "twotwo",
}
if err := json.NewEncoder(os.Stdout).Encode(res); err != nil {
panic(err)
}
Run Code Online (Sandbox Code Playgroud)
这将输出(直接到 Stdout):
{"one":1,"two":"twotwo"}
Run Code Online (Sandbox Code Playgroud)
如果要设置缩进,请使用其Encoder.SetIndent()方法:
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if err := enc.Encode(res); err != nil {
panic(err)
}
Run Code Online (Sandbox Code Playgroud)
这将输出:
{
"one": 1,
"two": "twotwo"
}
Run Code Online (Sandbox Code Playgroud)
试试Go Playground上的例子。
| 归档时间: |
|
| 查看次数: |
49 次 |
| 最近记录: |