Sadanand Upase Sadanand Upase - 15 days ago 5
JSON Question

How to unmarshal command line input properly?

I have written following code snippet in

trial.go
:

type Mine struct{
A string `json:"a"`
}

func main(){
s := Mine{}
v := os.Args[1]//`{"a":"1"}`
fmt.Println(v)
fmt.Println(reflect.TypeOf(v))
json.Unmarshal([]byte(v), &s)
fmt.Println(s)
}


I am running this file as below:

go run trial.go `{"A":"1"}`


But I don't get anything in
s
. It is always a blank struct.

What am I doing wrong here?

Answer

First check errors returned by json.Unmarshal().

Next your json tag uses small "a" as the JSON key, however the encoding/json package will recognize the capital "A" too.

And last passing such arguments in the command line may be OS specific. The backtick and quote usually have special meaning, try passing it like this:

go run trial.go {\"a\":\"1\"}
Comments