dongxiong4571 2013-06-12 00:43
浏览 105
已采纳

golang:在地图中快速访问地图数据

So I've got the following bit of JSON and I want to pull out the "$t" value under "token". Continue for Go code...

{
  "@encoding": "iso-8859-1",
  "@version": "1.0",
  "service": {
    "auth": {
      "expiresString": {
        "$t": "2013-06-12T01:15:28Z"
      },
      "token": {
        "$t": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
      },
      "expires": {
        "$t": "1370999728"
      },
      "key": {
        "$t": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
      }
    }
}

I have the following snippet of Go code that unmarshals the json into an interface. Then I work my way down to the "$t" value of "token". This approach does work, but it's ugly.

My question: is there a faster way to access that value than by converting each map into an interface? I'm very new to Go and am not aware of many of the useful features of interfaces and maps.

var f interface{}
jerr := json.Unmarshal(body, &f)
m := f.(map[string]interface{})
ser := m["service"].(map[string]interface{})
a := ser["auth"].(map[string]interface{})
tok := a["token"].(map[string]interface{})
token := tok["$t"]
fmt.Fprintf(w, "Token: %v
", token)

Thanks in advance!

  • 写回答

2条回答 默认 最新

  • dtx6087 2013-06-12 01:01
    关注

    If that's the only value you want, then how about using an anonymous struct that defines the path to your data.

    var m = new(struct{Service struct{Auth struct{Token map[string]string}}})
    
    var err = json.Unmarshal([]byte(data), &m)
    
    fmt.Println(m.Service.Auth.Token["$t"], err)
    

    DEMO: http://play.golang.org/p/ZdKTzM5i57


    Instead of using a map for the innermost data, we could use another struct, but we'd need to provide a field tag to alias the name.

    var m = new(struct{Service struct{Auth struct{Token struct{T string `json:"$t"`}}}})
    
    var err = json.Unmarshal([]byte(data), &m)
    
    fmt.Println(m.Service.Auth.Token.T, err)
    

    DEMO: http://play.golang.org/p/NQTpaUvanx

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?