英文:
Is it possible to partially deserialise JSON into a struct in go?
问题
我需要与一个返回大量元素的 API 进行集成。
在 Go 的 json
库中,是否可以只选择我想要的字段,还是需要对整个响应进行反序列化?
英文:
I need to integrate with an API that returns loads of elements in its response.
Is it possible to cherry-pick just the fields I want with go's json
library or do I need to deserialise the entire response?
答案1
得分: 4
是的。
这是一个示例,其中json中有2个字段,但只解码一个字段:
jsonString := `{"a": 1, "b": 2}`
var rec struct {
A int `json:"a"`
}
err := json.Unmarshal([]byte(jsonString), &rec)
if err != nil {
log.Fatalf("json.Unmarshal() failed with '%s'\n", err)
}
fmt.Printf("rec: %+v\n", rec)
运行时输出:
rec: {A:1}
即json中的字段"a"被解码,而字段"b"被丢弃。
完整示例请参见:https://play.golang.org/p/89tu-ZC4pR
英文:
Yes.
Here's an example of having 2 fields in json and only decoding one:
jsonString := `{"a": 1, "b": 2}`
var rec struct {
A int `json:"a"`
}
err := json.Unmarshal([]byte(jsonString), &rec)
if err != nil {
log.Fatalf("json.Unmarshal() failed with '%s'\n", err)
}
fmt.Printf("rec: %+v\n", rec)
When run it prints:
rec: {A:1}
i.e. field "a" in json was decoded and field "b" was discarded.
See https://play.golang.org/p/89tu-ZC4pR for full example.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论