arrays - 使用结构变量数组访问结构变量golang

标签 arrays json go struct interface

func GetprofilesApi(c *gin.Context) {
var p Profile
profiles, err, count := p.GetProfiles()
if err != nil {
    log.Fatalln(err)
}

c.JSON(http.StatusOK, gin.H{
    "Number of Results": count,

    "profiles": profiles,
}) }

//Getprofiles() function
func (p *Profile) GetProfiles() (profiles []Profile, err error, count int) {
profiles = make([]Profile, 0)
rows, err := db.Query("SELECT id, firstname, lastname, email, username, phone, function  FROM profile")
defer rows.Close()

if err != nil {
    return
}
//counting rows

for rows.Next() {
    var profile Profile
    rows.Scan(&profile.ID, &profile.FirstName, &profile.LastName, &profile.Email, &profile.Username, &profile.Phone, &profile.Function)
    profiles = append(profiles, profile)
    count = count + 1
}
if err = rows.Err(); err != nil {
    return
}
return}

我在获取每个对象的用户名配置文件时遇到问题

您可能会看到 Getprofiles() 返回所有字段,因此在 GetprofilesApi() 中我只想返回 json 结果中的用户名字段

感谢您的任何建议!

配置文件结构是:

type Profile struct {
ID        int    `json:"id"`
FirstName string `json:"firstname"`
LastName  string `json:"lastname"`
Username  string `json:"username"`
Email     string `json:"email"`
Phone     string `json:"phone"`
Function  string `json:"function"`}

json result

最佳答案

json:"-" 标签排除了 JSON 编码和解码的字段。定义一个与 Person 具有相同字段的新类型,并改为对该类型的一个 slice 进行编码(为简洁起见,省略了一些字段):

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Profile struct {
    ID       int    `json:"id"`
    Username string `json:"username"`
    Email    string `json:"email"`
}

type ProfileSummary struct {
    ID       int    `json:"-"`
    Username string `json:"username"`
    Email    string `json:"-"`
}

func main() {
    var profiles []Profile
    profiles = append(profiles, Profile{Username: "john", Email: "john.doe@example.com"})
    profiles = append(profiles, Profile{Username: "jane", Email: "jane.doe@example.com"})

    summaries := make([]ProfileSummary, len(profiles))
    for i, p := range profiles {
            summaries[i] = ProfileSummary(p)
    }

    b, err := json.MarshalIndent(summaries, "", "  ")
    if err != nil {
            log.Fatal(err)
    }

    fmt.Println(string(b))
}

在 Playground 上试试:https://play.golang.org/p/y3gP5IZDWzl

关于arrays - 使用结构变量数组访问结构变量golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49432716/

相关文章:

c# - 反序列化导致列表条目的副本

amazon-web-services - 如何从 Go Lambda 函数返回 HTML?

javascript - 从两个数组生成 JSON

来自其他包的 golang 结构

go - 可汗学院重定向默认 URL Golang

javascript - 查找数组中重复的对象值并将它们合并 - JAVASCRIPT

c++ - 动态数组的排序算法编译器错误

c++ - 撤消或取消随机播放 C++ 随机播放函数

javascript - JavaScript 中的最小最大和 - 如何获取 5 元素数组中 4 个元素的最小和和最大和

php - 需要 json 解码为 php 变量示例