有没有一些库可以方便地在Go语言中操作JSON?

huangapple go评论90阅读模式
英文:

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"]}
&lt;nil&gt;
英文:

<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{}{
	&quot;apple&quot;: &quot;red&quot;,
	&quot;book&quot;: []interface{}{
		&quot;history&quot;, &quot;art&quot;, &quot;science&quot;,
	},
})
fmt.Println(err)

Output (try it on the Go Playground):

{&quot;apple&quot;:&quot;red&quot;,&quot;book&quot;:[&quot;history&quot;,&quot;art&quot;,&quot;science&quot;]}
&lt;nil&gt;

huangapple
  • 本文由 发表于 2017年2月17日 18:41:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/42295801.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定