json - 访问必要的字段 json golang

标签 json api go

我一直在尝试从第三方 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

这是一个可运行的例子,显示它按预期工作

https://play.golang.org/p/PwnSj03hnEV

关于json - 访问必要的字段 json golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51398322/

相关文章:

android - 如何在Android上解析 "unit-test"json(JSONObject == "null")?

ios - 使用 swift 下载并解析 JSON

javascript - 如何在 OOP 类中更新对象 json

jquery - 在 ASP.NET MVC 中将对象列表转换为 Json

c++ - 在对话框窗口上使用图标 C++ Win32 API

api - global_merge_vars 不起作用

api - 如何通过 Coinbase Api v2 发送 ping 通知?

google-app-engine - golang 数据存储结构 : keeping field unique and required

go - 在 Go 中,如何将函数的标准输出捕获到字符串中?

go - 结构中的 map[string]string