Sadanand Upase Sadanand Upase - 1 year ago 93
JSON Question

How to unmarshal command line input properly?

I have written following code snippet in


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

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

I am running this file as below:

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

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

What am I doing wrong here?

Answer Source

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\"}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download