gpt4 book ai didi

go - 为什么在 json.Unmarshal() 之后我得到一个空结构?

转载 作者:行者123 更新时间:2023-12-01 22:42:43 25 4
gpt4 key购买 nike

关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。












想改进这个问题?将问题更新为 on-topic对于堆栈溢出。

1年前关闭。




Improve this question




编码器。我完全是新手,对 json.Unmarshal 输出有点困惑:

package main

import (
"encoding/json"
"fmt"
)

func main() {
s := `[{"First":"James","Last":"Bond","Age":32,"Sayings":["Shaken, not stirred","Youth is no guarantee of innovation","In his majesty's royal service"]},{"First":"Miss","Last":"Moneypenny","Age":27,"Sayings":["James, it is soo good to see you","Would you like me to take care of that for you, James?","I would really prefer to be a secret agent myself."]},{"First":"M","Last":"Hmmmm","Age":54,"Sayings":["Oh, James. You didn't.","Dear God, what has James done now?","Can someone please tell me where James Bond is?"]}]`

var res []struct{}
err := json.Unmarshal([]byte(s), &res)

if err != nil {
fmt.Println(err)
}

fmt.Println(res)
}

输出:
[{} {} {}]

为什么是空的?
你可以在这里试试: https://play.golang.org/p/yztOLJADIXx

最佳答案

如果您想在不知道其字段的情况下解码 JSON 对象,请使用 map[string]interface{} :

package main

import (
"encoding/json"
"fmt"
)

func main() {
s := `[{"First":"James","Last":"Bond","Age":32,"Sayings":["Shaken, not stirred","Youth is no guarantee of innovation","In his majesty's royal service"]},{"First":"Miss","Last":"Moneypenny","Age":27,"Sayings":["James, it is soo good to see you","Would you like me to take care of that for you, James?","I would really prefer to be a secret agent myself."]},{"First":"M","Last":"Hmmmm","Age":54,"Sayings":["Oh, James. You didn't.","Dear God, what has James done now?","Can someone please tell me where James Bond is?"]}]`

var res []map[string]interface{}
err := json.Unmarshal([]byte(s), &res)

if err != nil {
fmt.Println(err)
}

fmt.Println(res)
}

在这里尝试: https://play.golang.org/p/iPlBgguE8Kk

但是,如果您知道要解码的字段的名称,则应该定义结构。在您的情况下,它看起来像这样:
type Person struct {
First string `json:"First"`
Last string `json:"Last"`
Age int `json:"Age"`
Sayings []string `json:"Sayings"`
}

在此处尝试此解决方案: https://play.golang.org/p/jCrCteYTaIf

关于go - 为什么在 json.Unmarshal() 之后我得到一个空结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61820900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com