json.Unmarshal json string to object is empty result [duplicate]

半世苍凉 提交于 2020-01-11 14:40:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!