英文:
Read a slice from a json file in golang
问题
如何在Golang中从json
文件中读取切片?例如,文件data.json
的内容如下:
["a","b","c","d"]
我尝试使用ioutil.ReadFile
来实现,但它返回的是一个字符串,而不是一个切片。我该如何读取我的切片?
注意:你可以将方括号[]
替换为花括号{}
。
我已经使用结构体完成了这个任务,但我不希望用户必须输入这些复杂的JSON内容。
英文:
How do I read a slice from a json
file in golang? For example, the file data.json
looks like this:
["a","b","c","d"]
I have tried using ioutil.ReadFile
to do this, but this returns a string, not a slice. How can I read my slice?
NOTE: You can sub the brackets []
for braces {}
I have done this using structs, but I don't want the user to have to type in this complicated json stuff
答案1
得分: 8
例如,
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
)
func main() {
data, err := ioutil.ReadFile("data.json")
if err != nil {
fmt.Println(err)
return
}
fmt.Print("data: ",string(data))
var slice []string
err = json.Unmarshal(data, &slice)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("slice: %q\n",slice)
}
输出:
$ cat data.json
["a","b","c","d"]
$ go run data.go
data: ["a","b","c","d"]
slice: ["a" "b" "c" "d"]
$
英文:
For example,
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
)
func main() {
data, err := ioutil.ReadFile("data.json")
if err != nil {
fmt.Println(err)
return
}
fmt.Print("data: ",string(data))
var slice []string
err = json.Unmarshal(data, &slice)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("slice: %q\n",slice)
}
Output:
$ cat data.json
["a","b","c","d"]
$ go run data.go
data: ["a","b","c","d"]
slice: ["a" "b" "c" "d"]
$
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论