如何正确解组命令行输入?

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?

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 (shell) specific. The backtick and quotes usually have special meaning, try passing it like this:

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

Also you should check the length of os.Args before indexing it, if the user does not provide any arguments, os.Args[1] will panic.

As you mentioned, you should find another way to test input JSON documents, this becomes unfeasible if the JSON text is larger, and also this is OS (shell) specific. A better way would be to read from the standard input or read from a file.