问题
I've got a very simple program like this:
package main
import (
"encoding/json"
"fmt"
)
type RunCommand struct{
level string `json:"level"`
caller string `json:"caller"`
msg string `json:"msg"`
cmd string `json:"cmd"`
}
func main() {
content := `{"level":"info","caller":"my.go:10","msg":"run","cmd":"--parse"}`
runCommand := RunCommand{}
e := json.Unmarshal([]byte(content), &runCommand)
if e != nil {
fmt.Println("Unmarshal error")
}
fmt.Println(runCommand.level)
}
I wish that I could parse out all the json fields inside "content" into "runCommand" object, but actually, the final "fmt.Println" prints nothing. Where did I get wrong?
回答1:
You have to have exported fields, like this:
type RunCommand struct{
Level string `json:"level"`
Caller string `json:"caller"`
Msg string `json:"msg"`
Cmd string `json:"cmd"`
}
and now you can use: fmt.Println(runCommand.Level)
otherwise json.Unmarshal
will ignore non-exported fields.
来源:https://stackoverflow.com/questions/57908166/json-unmarshal-json-string-to-object-is-empty-result