使用未知字段名解析JSON

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

Unmarshal JSON with unknown field name

问题

我有一个JSON对象,类似于这样:

{
"randomstring": {
"everything": "here",
"is": "known"
}
}

基本上,randomstring 对象内的所有内容都是已知的,我可以对其建模,但是 randomstring 本身是随机的。我知道它将是什么,但每次都不同。基本上,我需要的所有数据都在 randomstring 对象中。我该如何解析这种JSON以获取数据?

英文:

I have a JSON object, something like this:

{
    "randomstring": {
        "everything": "here",
        "is": "known"
    }
}

Basically everything inside the randomstring object is known, I can model that, but the randomstring itself is random. I know what it's going to be, but it's different every time. Basically all the data I need is in the randomstring object. How could I parse this kind of JSON to get the data?

答案1

得分: 6

使用一个键类型为string,值类型为包含所需字段的结构体的映射,就像Playground上的这个示例和下面的代码一样:

package main

import (
	"encoding/json"
	"fmt"
	"log"
)

type Item struct{ X int }

var x = []byte(`
	{"zbqnx": {"x": 3}}
`)

func main() {
	m := map[string]Item{}
	err := json.Unmarshal(x, &m)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(m)
}
英文:

Use a map where the key type is string and the value type is a struct with the fields you want, like in this example on the Playground and below:

package main

import (
	"encoding/json"
	"fmt"
	"log"
)

type Item struct{ X int }

var x = []byte(`{
	"zbqnx": {"x": 3}
}`)

func main() {
	m := map[string]Item{}
	err := json.Unmarshal(x, &m)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(m)
}

huangapple
  • 本文由 发表于 2016年11月13日 09:07:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/40569482.html
匿名

发表评论

匿名网友

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

确定