有人知道在Go中漂亮打印JSON输出的简单方法吗?
我想漂亮地打印json的结果。Marshal,以及格式化现有的JSON字符串,以便更容易阅读。
有人知道在Go中漂亮打印JSON输出的简单方法吗?
我想漂亮地打印json的结果。Marshal,以及格式化现有的JSON字符串,以便更容易阅读。
当前回答
package cube
import (
"encoding/json"
"fmt"
"github.com/magiconair/properties/assert"
"k8s.io/api/rbac/v1beta1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"testing"
)
func TestRole(t *testing.T) {
clusterRoleBind := &v1beta1.ClusterRoleBinding{
ObjectMeta: v1.ObjectMeta{
Name: "serviceaccounts-cluster-admin",
},
RoleRef: v1beta1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: "cluster-admin",
},
Subjects: []v1beta1.Subject{{
Kind: "Group",
APIGroup: "rbac.authorization.k8s.io",
Name: "system:serviceaccounts",
},
},
}
b, err := json.MarshalIndent(clusterRoleBind, "", " ")
assert.Equal(t, nil, err)
fmt.Println(string(b))
}
其他回答
MarshalIndent将允许您输出带有缩进和间距的JSON。例如:
{
"data": 1234
}
缩进参数指定要缩进的字符序列。因此,json。MarshalIndent(data, "", "")将使用四个空格进行缩进。
我很沮丧,因为在Go中缺少一种快速、高质量的方法来将JSON编组为彩色字符串,所以我写了自己的编组程序ColorJSON。
有了它,你可以用很少的代码轻松生成如下输出:
package main
import (
"fmt"
"encoding/json"
"github.com/TylerBrock/colorjson"
)
func main() {
str := `{
"str": "foo",
"num": 100,
"bool": false,
"null": null,
"array": ["foo", "bar", "baz"],
"obj": { "a": 1, "b": 2 }
}`
var obj map[string]interface{}
json.Unmarshal([]byte(str), &obj)
// Make a custom formatter with indent set
f := colorjson.NewFormatter()
f.Indent = 4
// Marshall the Colorized JSON
s, _ := f.Marshal(obj)
fmt.Println(string(s))
}
我现在正在为它写文档,但我很高兴能分享我的解决方案。
回头看,这是非惯用的围棋。像这样的小助手函数增加了额外的复杂性。一般来说,围棋哲学倾向于包含3条简单的线,而不是1条棘手的线。
正如@robyoder提到的,json。缩进才是正确的选择。我想添加这个小的prettyprint函数:
package main
import (
"bytes"
"encoding/json"
"fmt"
)
//dont do this, see above edit
func prettyprint(b []byte) ([]byte, error) {
var out bytes.Buffer
err := json.Indent(&out, b, "", " ")
return out.Bytes(), err
}
func main() {
b := []byte(`{"hello": "123"}`)
b, _ = prettyprint(b)
fmt.Printf("%s", b)
}
https://go-sandbox.com/#/R4LWpkkHIN或http://play.golang.org/p/R4LWpkkHIN
package cube
import (
"encoding/json"
"fmt"
"github.com/magiconair/properties/assert"
"k8s.io/api/rbac/v1beta1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"testing"
)
func TestRole(t *testing.T) {
clusterRoleBind := &v1beta1.ClusterRoleBinding{
ObjectMeta: v1.ObjectMeta{
Name: "serviceaccounts-cluster-admin",
},
RoleRef: v1beta1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: "cluster-admin",
},
Subjects: []v1beta1.Subject{{
Kind: "Group",
APIGroup: "rbac.authorization.k8s.io",
Name: "system:serviceaccounts",
},
},
}
b, err := json.MarshalIndent(clusterRoleBind, "", " ")
assert.Equal(t, nil, err)
fmt.Println(string(b))
}
使用json。带字符串的MarshalIndent
这个easyPrint函数接受参数数据(任何类型的数据),并将其打印成预期的(漂亮的)JSON格式。
import (
"encoding/json"
"log"
)
func easyPrint(data interface{}) {
manifestJson, _ := json.MarshalIndent(data, "", " ")
log.Println(string(manifestJson))
}
使用name参数。
TODO:使参数名可选。
func easyPrint(data interface{}, name string) {
manifestJson, _ := json.MarshalIndent(data, "", " ")
log.Println(name + " ->", string(manifestJson))
}