Create a JSON or slice array in Go

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

Create a JSON or slice array in Go

问题

我不确定如何做或者如何表达。我有一个返回字符串的变量,类似这样:

unixCommands := exec.Command("ls", "/bin")
unixCommandsout, err := unixCommands.Output()
unixCommandsstring := string(unixCommandsout)
fmt.Printf(unixCommandsstring)

输出:

unicode_start
unicode_stop
unlink
usleep
vi
view
ypdomainname
zcat

我想要创建一个JSON数组或者其他最简单的方式来得到最终输出:

["unicode_start", "unicode_stop", "unlink", "usleep", "vi", "view", "ypdomainname", "zcat"]
英文:

I am not sure how to do this or word this. I have a variable that returns a string something like this:

unixCommands := exec.Command("ls", "/bin")
unixCommandsout, err := unixCommands.Output()
unixCommandsstring := string(unixCommandsout)
fmt.Printf(unixCommandsstring)

Output:

unicode_start
unicode_stop
unlink
usleep
vi
view
ypdomainname
zcat

I'm looking for creating a JSON array or whatever is easiest to get to this final output:

["unicode_start", "unicode_stop", "unlink", "usleep", "vi", "view", "ypdomainname", "zcat"]

答案1

得分: 1

你可以使用encoding/json包来实现:

outputSlice := strings.Split(unixCommandsstring, "\n")
js, _ := json.Marshal(outputSlice)
fmt.Print(string(js))

这段代码将unixCommandsstring按换行符分割成一个切片outputSlice,然后使用json.Marshal将切片转换为JSON格式的字符串,最后使用fmt.Print打印输出。

英文:

You can do that with package encoding/json:

outputSlice := strings.Split(unixCommandsstring,"\n")
js,_ := json.Marshal(outputSlice)
fmt.Print(string(js))

huangapple
  • 本文由 发表于 2015年4月14日 10:59:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/29618428.html
匿名

发表评论

匿名网友

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

确定