英文:
Json Marshalling straight to stdout
问题
我正在尝试学习Golang,在此过程中,我编写了下面的代码(作为一个更大的自学项目的一部分),并向陌生人请教了代码审查,其中一个评论是:“你可以直接将其编组到stdout,而不是编组到堆上,然后将其转换为字符串,再将其流式传输到stdout”。
我已经阅读了encoding/json
包和io
的文档,但无法理清所需的更改。
任何指针或帮助都将非常感谢。
// 使用适当的制表符缩进对结构进行编组,以便可读性更强
b, err := json.MarshalIndent(res, "", " ")
if err != nil {
log.Fatal(errors.Wrap(err, "error marshaling response data"))
}
// 将输出打印到stdout
fmt.Fprint(os.Stdout, string(b))
编辑
我刚在文档中找到了以下代码示例:
var out bytes.Buffer
json.Indent(&out, b, "=", "\t")
out.WriteTo(os.Stdout)
但是它在写入stdout
之前仍然先写入堆。不过,它确实省去了将其转换为字符串的一步。
英文:
I am trying to learn Golang and while doing that I wrote below code (part of bigger self learning project) and took the code review from strangers, one of the comment was, "you could have marshalled this straight to stdout, instead of marshalling to heap, then converting to string and then streaming it to stdout"
I have gone through the documentation of encoding/json
package and io
but not able to piece together the change which is required.
Any pointers or help would be great.
// 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))
EDIT
I just found below code sample in documentation:
var out bytes.Buffer
json.Indent(&out, b, "=", "\t")
out.WriteTo(os.Stdout)
But again it writes to heap first before writing to stdout
. It does remove one step of converting it to string though.
答案1
得分: 7
创建并使用一个指向os.Stdout
的json.Encoder
。json.NewEncoder()
接受任何io.Writer
作为其目标。
res := map[string]interface{}{
"one": 1,
"two": "twotwo",
}
if err := json.NewEncoder(os.Stdout).Encode(res); err != nil {
panic(err)
}
这将直接输出到标准输出(Stdout):
{"one":1,"two":"twotwo"}
如果你想设置缩进,可以使用它的Encoder.SetIndent()
方法:
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if err := enc.Encode(res); err != nil {
panic(err)
}
这将输出:
{
"one": 1,
"two": "twotwo"
}
在Go Playground上尝试这些示例。
英文:
Create and use a json.Encoder
directed to os.Stdout
. json.NewEncoder()
accepts any io.Writer
as its destination.
res := map[string]interface{}{
"one": 1,
"two": "twotwo",
}
if err := json.NewEncoder(os.Stdout).Encode(res); err != nil {
panic(err)
}
This will output (directly to Stdout):
{"one":1,"two":"twotwo"}
If you want to set indentation, use its Encoder.SetIndent()
method:
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if err := enc.Encode(res); err != nil {
panic(err)
}
This will output:
{
"one": 1,
"two": "twotwo"
}
Try the examples on the Go Playground.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论