如何读取 3 个 json 文件

我正在尝试从 3 个不同的 json 文件中读取 json 数据,其中 json 文件名为 student1.json、students2.json,第三个是 interns.json。我的第一个问题:我在 errr 中遇到错误:= json.Unmarshal(Database, &database) 错误是(类型数据库不是表达式)


第二个问题:我不知道如何将第三个json文件与另一个添加(一个具有不同的名称interns.json)


这是我的代码:


type Database struct {

    FirstName string `json:"first"`

    LastName  string `json:"last"`

    Email string `json:"email"`

}


func main() {

fileIndex := 1 // 2 json file

for i := 1; i <= fileIndex; i++ {

    fileName := fmt.Sprintf("%s%d%s", "students", i, ".json")


    // open json file

    jsonFile, err := os.Open(fileName)


    defer jsonFile.Close()

    byteValue, _ := ioutil.ReadAll(jsonFile)

    var database []Database

    json.Unmarshal(byteValue, &database)

    errr := json.Unmarshal(Database, &database)

    if errr != nil {

        panic(errr)

    }

}

}

谁能帮我?谢谢!


绝地无双
浏览 124回答 1
1回答

长风秋雁

您可以将文件名放入一个切片中,也可以将Database. 然后只需将文件和unmarshal它们读入Database.func main() {&nbsp; &nbsp; fileNames := []string{"students1.json", "students2.json", "interns.json"}&nbsp; &nbsp; databases := []Database{}&nbsp; &nbsp; for _, file := range fileNames {&nbsp; &nbsp; &nbsp; &nbsp; jsonData, err := ioutil.ReadFile(file)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; db := Database{}&nbsp; &nbsp; &nbsp; &nbsp; err = json.Unmarshal(jsonData, &db)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; databases = append(databases, db)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(databases)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go