如何在函数中将结构字段作为参数传递以显示 json 数据?

我正在做一个项目来显示 json 数据并检查它们是否是闰年。


我正在尝试为IsLeapYear创建一个参数,以便在进行测试时可以传入一些 json 值,我尝试使用User指向结构的指针,以便可以传入函数参数中的字段,但它不起作用.


如何在函数参数中传递来自 user.json 的 json 数据,这样我可以更轻松地进行测试?


只是为了让您知道,我的测试文件中出现错误,因为我创建了 DateTest 字符串,但IsLeapYear不是字符串。


这是我的代码:


main.go:


  package main


import (

    "encoding/json"

    "fmt"

    "io/ioutil"

    "log"

    "os"

    "time"

)


// Users struct which contains

// an array of users

type Users struct {

    Users []User `json:"users"`

}


// User struct which contains a name

// a type and a list of social links

type User struct {

    Firstname  string `json:"fname"`

    Secondname string `json:"lname"`

    Date       string `json:"date"`

}


var users Users


func Birthday() {

    // Open our jsonFile

    jsonFile, err := os.Open("users.json")

    // if we os.Open returns an error then handle it

    if err != nil {

        fmt.Println(err)

    }


    fmt.Println("Successfully Opened users.json")

    // defer the closing of our jsonFile so that we can parse it later on

    defer jsonFile.Close()


    // read our opened xmlFile as a byte array.

    byteValue, _ := ioutil.ReadAll(jsonFile)


    // we initialize our Users array

    // we unmarshal our byteArray which contains our

    // jsonFile's content into 'users' which we defined above

    json.Unmarshal(byteValue, &users)


    IsLeapYear(&users{Firstname: ""}, &users{Secondname: ""}) ---> passing the users fileds 

}


func IsLeapYear(firstname *Users, secondname *Users) {


    // we iterate through every user within our users array and

    // print out the user Type, their name

    for i := 0; i < len(users.Users); i++ {

        date, err := time.Parse("2006/01/02", users.Users[i].Date)

        if err != nil {

            date, err = time.Parse("2006-01-02", users.Users[i].Date)

            // date, err = time.Parse("2006 01 02", users.Users[i].Date)

            if err != nil {

                log.Fatal("unsupported date format:", err)

            }

        }


紫衣仙女
浏览 65回答 1
1回答

拉风的咖菲猫

在这里,我清理了你的代码。现在测试应该更容易编写package mainimport (&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "io/ioutil"&nbsp; &nbsp; "log"&nbsp; &nbsp; "os"&nbsp; &nbsp; "time")// Data struct which contains// an array of userstype Data struct {&nbsp; &nbsp; Users []User `json:"users"`}// User struct which contains the first + last name and the birthdatetype User struct {&nbsp; &nbsp; FirstName&nbsp; string `json:"first_name"`&nbsp; &nbsp; LastName string `json:"last_name"`&nbsp; &nbsp; Date&nbsp; &nbsp; &nbsp; &nbsp;string `json:"date"`}func IsLeapYear(date time.Time) bool {&nbsp; &nbsp; return date.Day()%400 == 0 || (date.Day()%4 == 0 && date.Day()%100 != 0)}func parseDate(date string) time.Time {&nbsp; &nbsp; parsedDate, err := time.Parse("2006/01/02", date)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; parsedDate, err = time.Parse("2006-01-02", date)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Fatal("unsupported date format:", err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return parsedDate}func CheckBirthdateOf(user User) {&nbsp; &nbsp; date := parseDate(user.Date)&nbsp; &nbsp; fmt.Println("User Date: " + user.Date)&nbsp; &nbsp; fmt.Println("User First Name: " + user.FirstName)&nbsp; &nbsp; fmt.Println("User Last Name: " + user.LastName)&nbsp; &nbsp; if IsLeapYear(date) {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(user.Date, "is a Leap Year ✨ ✨ ✨")&nbsp; &nbsp; &nbsp; &nbsp; if date.Day() == time.Now().Day() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("TODAY IS YOUR BIRTHDAY AND A Leap YEAR, Happy birthday !!!🎉 🎉 🍾 🍾 ")&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("TODAY IS NOT YOUR BIRTHDAY, but it's a leap year..!!! 👍 👍 👍 ")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(user.Date, " is Not a Leap Year 💥 💥 💥 ")&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Your Date is neither a leap year nor your birthday..!!! 😔😔😔")&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println("")}func main() {&nbsp; &nbsp; jsonFile, err := os.Open("users.json")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println("Successfully Opened users_data.json")&nbsp; &nbsp; defer jsonFile.Close()&nbsp; &nbsp; byteValue, _ := ioutil.ReadAll(jsonFile)&nbsp; &nbsp; var usersData Data&nbsp; &nbsp; json.Unmarshal(byteValue, &usersData)&nbsp; &nbsp; for _, user := range usersData.Users {&nbsp; &nbsp; &nbsp; &nbsp; CheckBirthdateOf(user)&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go