我正在尝试学习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 关注
- 99 浏览
添加回答
举报
0/150
	提交
		取消
	