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

huangapple go评论65阅读模式
英文:

How to unmarshal command line input properly?

问题

我已经在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)    
}

我以以下方式运行这个文件:

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

但是我在s中没有得到任何内容。它始终是一个空的结构体。

我在这里做错了什么?

英文:

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?

答案1

得分: 1

首先检查json.Unmarshal()返回的错误。

接下来,你的json标签使用小写的"a"作为JSON键,然而encoding/json包也会识别大写的"A"

最后,在命令行中传递这样的参数可能是特定于操作系统(shell)的。反引号和引号通常具有特殊含义,尝试像这样传递它:

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

此外,在索引os.Args之前,你应该检查其长度,如果用户没有提供任何参数,os.Args[1]将会引发恐慌。

正如你提到的,你应该找到另一种测试输入JSON文档的方法,如果JSON文本较大,这种方法将变得不可行,而且这也是特定于操作系统(shell)的。更好的方法是从标准输入读取或从文件中读取。

英文:

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.

huangapple
  • 本文由 发表于 2016年11月18日 11:31:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/40668910.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定