从文件 Golang 加载 json 时没有值



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

我有一个项目,我正在尝试将 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 结构字段标签。例如

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: %dn", 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"
]
}
]

最新更新