是否有一些lib可以在golang中促进JSON的操作?

时间:2017-02-17 10:41:03

标签: python json go

当我编写python时,我喜欢这样做:

d = {"apple": "red", "book":["history", "art", "science"]}
print json.JSONEncoder().encode(d)

然后我得到JSON字符串

'{"apple":"red","book":["history","art","science"]}'

但是当我想在Golang中这样做时,事情变得更复杂,我必须首先定义结构:

type Gadget struct {
    Apple string
    Book []string
}
g := Gadget{Apple: "red", Book: []string{"history", "art", "science"}}
bytes, _ := json.Marshal(g)
fmt.Println(string(bytes))

是否有一些golang lib可以帮助我操作像python这样的JSON字符串? 我可能有很多JSON,它们有不同的结构来处理。定义它们都是一项繁琐的工作。我甚至认为没有lib,因为golang中没有索引操作符重载机制。

你们说什么?

1 个答案:

答案 0 :(得分:6)

问题是偏离主题,因为它要求异地资源,但可以使用标准库来解决,所以:

您不需要结构,您可以使用可以为所有数据结构建模的嵌入式地图和切片。

你的例子:

err := json.NewEncoder(os.Stdout).Encode(map[string]interface{}{
    "apple": "red",
    "book": []interface{}{
        "history", "art", "science",
    },
})
fmt.Println(err)

输出(在Go Playground上尝试):

{"apple":"red","book":["history","art","science"]}
<nil>
相关问题