英文:
Is there some lib can facilitate the OPERATIONS of JSON in golang?
问题
当我写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库可以帮助我像Python那样操作JSON字符串?我可能有许多具有不同结构的JSON需要处理。定义它们都是一项繁琐的工作。我甚至不认为有一个库,因为Golang中没有索引操作符重载机制。
你们有什么建议?
英文:
When I write python, I like to do that:
d = {"apple": "red", "book":["history", "art", "science"]}
print json.JSONEncoder().encode(d)
then I get the JSON string
'{"apple":"red","book":["history","art","science"]}'
but when I want to do that in Golang, things get more complicated, I have to define the struct first:
type Gadget struct {
Apple string
Book []string
}
g := Gadget{Apple: "red", Book: []string{"history", "art", "science"}}
bytes, _ := json.Marshal(g)
fmt.Println(string(bytes))
Is there some golang lib that can help me manipulate the JSON string like python?
I may have many JSON which have different struct to deal with. To define them all is a fussy work. I don't even think there's a lib cause there is no index operater overloading mechanism in golang.
What do you guys say?
答案1
得分: 6
<sup>问题是离题的,因为它要求使用外部资源,但可以使用标准库来解决:</sup>
你不需要一个结构体,你可以使用嵌套的映射和切片来模拟所有的数据结构。
你的例子:
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>
英文:
<sup>Question would be off-topic as it asks for off-site resources, but it can be solved using the standard lib, so:</sup>
You don't need a struct, you can just use embedded maps and slices which can model all data structures.
Your example:
err := json.NewEncoder(os.Stdout).Encode(map[string]interface{}{
"apple": "red",
"book": []interface{}{
"history", "art", "science",
},
})
fmt.Println(err)
Output (try it on the Go Playground):
{"apple":"red","book":["history","art","science"]}
<nil>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论