gpt4 book ai didi

json - 从文件 Golang 加载 Json 时没有值

转载 作者:IT王子 更新时间:2023-10-29 01:53:50 26 4
gpt4 key购买 nike

我希望有人能帮我解决这个问题,因为我已经摸不着头脑了一段时间。

我有一个项目,我正在尝试将 json 加载到 go 中的结构中。我完全按照几个在线教程进行了操作,但一直没有返回任何数据,也没有出现任何错误。

我的 json 文件名为 page_data.json,如下所示:

[
{
"page_title": "Page1",
"page_description": "Introduction",
"link": "example_link",
"authors":
[
"Author1",
"Author2",
"Author3",
]
},
// second object, same as the first
]

但是当我在 go 中尝试以下操作时:

package main

import (
"fmt"
"encoding/json"
"os"
"io/ioutil"
)

type PageData struct {
Title string `json: "page_title"`
Description string `json: "page_description"`
Link string `json: "link"`
Authors []string `json: "authors"`
}

func main() {
var numPages int = LoadPageData("page_data.json")
fmt.Printf("Num Pages: %d", numPages)
}

func LoadPageData(path string) int {
jsonFile, err := os.Open(path)
if err != nil {
fmt.Println(err)
}
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)

var pageList []PageData

json.Unmarshal(byteValue, &pageList)
return len(pageList)
}

我得到的输出是:

页数:0

最佳答案

修复 JSON 逗号和 Go struct 字段标签。例如,

package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)

type PageData struct {
Title string `json:"page_title"`
Description string `json:"page_description"`
Link string `json:"link"`
Authors []string `json:"authors"`
}

func main() {
var numPages int = LoadPageData("page_data.json")
fmt.Printf("Num Pages: %d\n", numPages)
}

func LoadPageData(path string) int {
jsonFile, err := os.Open(path)
if err != nil {
fmt.Println(err)
}
defer jsonFile.Close()
byteValue, err := ioutil.ReadAll(jsonFile)
if err != nil {
fmt.Println(err)
}
var pageList []PageData

err = json.Unmarshal(byteValue, &pageList)
if err != nil {
fmt.Println(err)
}

fmt.Println(pageList)

return len(pageList)
}

输出:

[{Page1 Introduction example_link [Author1 Author2 Author3]}]

page_data.json:

[
{
"page_title": "Page1",
"page_description": "Introduction",
"link": "example_link",
"authors":
[
"Author1",
"Author2",
"Author3"
]
}
]

关于json - 从文件 Golang 加载 Json 时没有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52845294/

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