Read a slice from a json file in golang

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

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"]
$

huangapple
  • 本文由 发表于 2016年3月21日 04:40:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/36119284.html
匿名

发表评论

匿名网友

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

确定