How to Unmarshal jSON with dynamic key which can't be captured as a `json` in struct: GOlang [duplicate]

∥☆過路亽.° 提交于 2019-12-30 11:03:07

问题


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?


回答1:


Use a map:

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

playground example



来源:https://stackoverflow.com/questions/35558039/how-to-unmarshal-json-with-dynamic-key-which-cant-be-captured-as-a-json-in-st

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!