我一直在尝试从第三方 API 访问字段。 例如来自第三方 api 的 json 响应是这样的:
{
"request_id": "bba3b69370774f87bed0e70398a97f45",
"account_id": "2c1cd618",
"number": "6289523686433"
}
我只想获取request_id 我可以只像这样创建界面吗:
type Response struct {
RequestID string json:"request_id"
}
然后这样做:
var resp Response
json.Unmarshal(body,&resp)
这有可能吗?或者我是否需要在 Response 结构中创建响应主体的所有字段才能解码? 谢谢
最佳答案
来自 json.Unmarshal
文档
By default, object keys which don't have a corresponding struct field are ignored (see Decoder.DisallowUnknownFields for an alternative).
https://golang.org/pkg/encoding/json/#Unmarshal
这是一个可运行的例子,显示它按预期工作
关于json - 访问必要的字段 json golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51398322/