gpt4 book ai didi

json - 当我尝试用 go lang 调用值时出错

转载 作者:IT王子 更新时间:2023-10-29 02:32:03 24 4
gpt4 key购买 nike

我刚开始学习这个 Go Lang 编程,现在我被 [] 东西​​困住了,我尝试使用 Go Lang 创建一个博客并且我使用的是模板,模板没有问题,它只是我想附加一个我从 json 文件中获得的数据。

如果我只是获取数据并通过文件发送它已经完成,但问题是当我尝试将 slug 附加到数据时(因为我在 json 文件中没有 slug url。

这就是为什么我想得到帖子的标题,然后用它做一个 slug,然后

package main

import (
"encoding/json"
"fmt"
"github.com/gosimple/slug"
"html/template"
"io/ioutil"
"net/http"
"os"
)

type Blog struct {
Title string
Author string
Header string
}

type Posts struct {
Posts []Post `json:"posts"`
}

type Post struct {
Title string `json:"title"`
Author string `json:"author"`
Content string `json:"content"`
PublishDate string `json:"publishdate"`
Image string `json:"image"`
}

type BlogViewModel struct {
Blog Blog
Posts []Post
}

func loadFile(fileName string) (string, error) {
bytes, err := ioutil.ReadFile(fileName)

if err != nil {
return "", err
}

return string(bytes), nil
}

func loadPosts() []Post {
jsonFile, err := os.Open("source/posts.json")
if err != nil {
fmt.Println(err)
}

fmt.Println("Successfully open the json file")
defer jsonFile.Close()

bytes, _ := ioutil.ReadAll(jsonFile)

var post []Post
json.Unmarshal(bytes, &post)

return post
}

func handler(w http.ResponseWriter, r *http.Request) {
blog := Blog{Title: "asd", Author: "qwe", Header: "zxc"}
posts := loadPosts()

viewModel := BlogViewModel{Blog: blog, Posts: posts}

t, _ := template.ParseFiles("template/blog.html")
t.Execute(w, viewModel)
}

错误显示在主函数中

func main() {

posts := loadPosts()

for i := 0; i < len(posts.Post); i++ { // it gives me this error posts.Post undefined (type []Post has no field or method Post)

fmt.Println("Title: " + posts.Post[i].Title)
}
// http.HandleFunc("/", handler)

// fs := http.FileServer(http.Dir("template"))
// http.Handle("/assets/css/", fs)
// http.Handle("/assets/js/", fs)
// http.Handle("/assets/fonts/", fs)
// http.Handle("/assets/images/", fs)
// http.Handle("/assets/media/", fs)

// fmt.Println(http.ListenAndServe(":9000", nil))

}

我已经尝试解决了几个小时,但我碰壁了,我认为这是可能的,但我只是找不到方法,我不知道解决问题的好关键字是什么。如果我已经解释得足够好,我不会。请帮帮我,谢谢

这是JSON文件格式

{
"posts": [
{
"title": "sapien ut nunc",
"author": "Jeni",
"content": "jgwilt0@mapquest.com",
"publishdate": "26.04.2017",
"image": "http://dummyimage.com/188x199.png/cc0000/ffffff"
},
{
"title": "mus vivamus vestibulum sagittis",
"author": "Analise",
"content": "adonnellan1@biblegateway.com",
"publishdate": "13.03.2017",
"image": "http://dummyimage.com/182x113.bmp/ff4444/ffffff"
}
]
}

This is the directory

最佳答案

您正在 loadPost 方法返回 []Post。您的 Post 定义不包含 attribute Post。您的 Posts 结构可以。

这是一个修改后的工作示例。为简洁起见,我没有定义您的其他结构。

package main

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

var rawJson = `{
"posts": [
{
"title": "sapien ut nunc",
"author": "Jeni",
"content": "jgwilt0@mapquest.com",
"publishdate": "26.04.2017",
"image": "http://dummyimage.com/188x199.png/cc0000/ffffff"
},
{
"title": "mus vivamus vestibulum sagittis",
"author": "Analise",
"content": "adonnellan1@biblegateway.com",
"publishdate": "13.03.2017",
"image": "http://dummyimage.com/182x113.bmp/ff4444/ffffff"
}
]
}`

type Data struct {
Posts []struct {
Title string `json:"title"`
Author string `json:"author"`
Content string `json:"content"`
Publishdate string `json:"publishdate"`
Image string `json:"image"`
} `json:"posts"`
}

func loadFile(fileName string) (string, error) {
bytes, err := ioutil.ReadFile(fileName)

if err != nil {
return "", err
}
return string(bytes), nil
}

func loadData() (Data, error) {
var d Data
// this is commented out so that i can load raw bytes as an example
/*
f, err := os.Open("source/posts.json")
if err != nil {
return d, err
}
defer f.Close()

bytes, _ := ioutil.ReadAll(f)
*/

// replace rawJson with bytes in prod
json.Unmarshal([]byte(rawJson), &d)
return d, nil
}

func main() {
data, err := loadData()
if err != nil {
log.Fatal(err)
}

for i := 0; i < len(data.Posts); i++ {
fmt.Println("Title: " + data.Posts[i].Title)
}

/*
// you can also range over the data.Posts if you are not modifying the data then using the index is not necessary.
for _, post := range data.Posts {
fmt.Println("Title: " + post.Title)
}
*/

}

只为文件修改

package main

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

type Data struct {
Posts []struct {
Title string `json:"title"`
Author string `json:"author"`
Content string `json:"content"`
Publishdate string `json:"publishdate"`
Image string `json:"image"`
} `json:"posts"`
}


func loadData() (Data, error) {
var d Data
b, err := ioutil.ReadFile("source/posts.json")
if err != nil {
return d, err
}

err = json.Unmarshal(b, &d)
if err != nil {
return d, err
}

return d, nil
}

func main() {
data, err := loadData()
if err != nil {
log.Fatal(err)
}

for _, post := range data.Posts {
fmt.Println("Title: " + post.Title)
}
}

关于json - 当我尝试用 go lang 调用值时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48030870/

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