duanjizi9443 2016-02-22 07:53
浏览 32
已采纳

如何使用无法在结构中捕获为动态JSON的动态密钥解组jSON:GOlang [重复]

This question already has an answer here:

I have this struct defined:

type X struct {
 A string `json:"a_known_string"`
 B string `json:"b_known_string"`
}

This sample JSON:

jsnStr := [read in from a file and printed out to confirm]

It is:

{
 "any string" : {
   "a_known_string" : "some value",
   "b_known_string" : "another value" 
 }
}

If it was just the struct, I could:

var x X
err := json.Unmarshal(jsnStr, &x)

But I need to capture that 'any string'. How do I do that please?

</div>
  • 写回答

1条回答 默认 最新

  • duanbairan4235 2016-02-22 07:58
    关注

    Use a map:

    var m map[string]X
    err := json.Unmarshal([]byte(jsnStr), &m)
    

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部