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

huangapple go评论75阅读模式
英文:

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

问题

我有这个定义的结构体:

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

这是一个示例的JSON:

jsnStr := [从文件中读取并打印出来确认]

它是这样的:

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

如果只有结构体,我可以这样做:

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

但我需要捕获那个 'any string'。
请问我该如何做?

英文:

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

得分: 4

使用地图:

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

playground示例

英文:

Use a map:

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

playground example

huangapple
  • 本文由 发表于 2016年2月22日 23:53:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/35558039.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定