dev_medo
dev_medo

Reputation: 41

Accessing a struct variable with an array of structs variables golang

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}

i have a problem to get just a username profile for each object

as you may see the Getprofiles()return all the fields so in the GetprofilesApi() i want to be returned just the username field in the json result

Thanks for any suggestions!!

the profile struct is :

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

Upvotes: 0

Views: 3603

Answers (1)

Peter
Peter

Reputation: 31681

The json:"-" tags excludes a field for JSON marshaling and unmarshaling. Define a new type that has the same fields as Person, and encode a slice of that type instead (omitting some fields for brevity):

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: "[email protected]"})
    profiles = append(profiles, Profile{Username: "jane", Email: "[email protected]"})

    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))
}

Try it on the playground: https://play.golang.org/p/y3gP5IZDWzl

Upvotes: 2

Related Questions