-2

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Troskyvs
  • 7,537
  • 7
  • 47
  • 115

1 Answers1

4

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.

cn007b
  • 16,596
  • 7
  • 59
  • 74