英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论