从文件Golang加载Json时没有值

时间:2018-10-16 23:27:18

标签: json go

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

我有一个项目,正在尝试将json加载到结构中。我已经在网上完全按照几个教程进行操作,但是一直没有返回任何数据,也没有错误。

我的json文件称为page_data.json,看起来像:

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

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

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

1 个答案:

答案 0 :(得分:4)

修复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"
        ]
    }
]