gpt4 book ai didi

json - 如何读取多个json文件

转载 作者:数据小太阳 更新时间:2023-10-29 03:39:22 28 4
gpt4 key购买 nike

我正在尝试从多个 json 文件中读取 json 数据。我不确定如何读取每个文件并连接所有结果

json 文件名是 test1.json、test2.json、test3.json..etc,具有相同的数据结构,但我在读取所有内容时遇到问题,我的代码似乎只显示最后一个。我已经根据文件名连接了一个字符串,但似乎对我不起作用。

type Book struct {
Id string `json: "id"`
Title string `json: "title"`
}

func main() {
fileIndex := 2 // three json files. All named test1.json, test2.json and test3.json

var master []Book

for i := 0; i <= fileIndex; i++ {
fileName := fmt.Sprintf("%s%d%s", "test", fileIndex, ".json")

// Open jsonFile
jsonFile, err := os.Open(fileName)

defer jsonFile.Close()

byteValue, _ := ioutil.ReadAll(jsonFile)
fmt.Println(byteValue)
var book []Book

json.Unmarshal(byteValue, &book)
fmt.Println(book) // all print shows the test3.json result
}
}

我需要能够读取所有三个 json 文件并希望连接所有结果。谁能帮我?谢谢!

最佳答案

您在生成文件名时使用 fileIndex 而不是在 for 循环中使用 i。更改后的代码为:

type Book struct {
Id string `json: "id"`
Title string `json: "title"`
}

func main() {
fileIndex := 2 // three json files. All named test1.json, test2.json and test3.json

var master []Book

for i := 0; i <= fileIndex; i++ {
fileName := fmt.Sprintf("%s%d%s", "test", i, ".json")

// Open jsonFile
jsonFile, err := os.Open(fileName)

defer jsonFile.Close()

byteValue, _ := ioutil.ReadAll(jsonFile)
fmt.Println(byteValue)
var book []Book

json.Unmarshal(byteValue, &book)
fmt.Println(book)
}
}

此外,您可以在 for 循环中执行类似 master = append(master, book) 的操作,以最终获取 master 中的所有 JSON 内容

关于json - 如何读取多个json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57472008/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com