Home > Software design >  How to remove duplicate json information on struct
How to remove duplicate json information on struct

Time:07-26

I have the following code that works


type Q struct {
    Links struct {
        Self struct {
            Href string `json:"href"`
        } `json:"self"`
    } `json:"_links"`
    CreatedAt time.Time `json:"created_at"`
    ID        uuid.UUID `json:"id"`
    Name      string    `json:"name"`
    UpdatedAt time.Time `json:"updated_at"`
}

expected, _ := json.Marshal(Q{Links: struct {
    Self struct {
        Href string `json:"href"`
    } `json:"self"`
}{
    Self: struct {
        Href string `json:"href"`
    }{
        Href: url,
    },
},
    ID:        id,
    Name:      name,
    CreatedAt: now,
    UpdatedAt: now,
})

However, I find bad the repeteation of json fields, it is possible to remove it from expected? If I remove it returns an error

CodePudding user response:

Declaring each struct as a named type will avoid having to rewrite the whole struct type repeatedly:

type Q struct {
    Links     Links     `json:"_links"`
    CreatedAt time.Time `json:"created_at"`
    ID        string    `json:"id"`
    Name      string    `json:"name"`
    UpdatedAt time.Time `json:"updated_at"`
}

type Links struct {
    Self Self `json:"self"`
}

type Self struct {
    Href string `json:"href"`
}

func main() {

    expected, _ := json.Marshal(
        Q{Links: Links{
            Self: Self{
                Href: "testurl",
            },
        },
            ID:        "testid",
            Name:      "testname",
            CreatedAt: time.Now(),
            UpdatedAt: time.Now(),
        })

    fmt.Println(string(expected))
}

Go Playground

  •  Tags:  
  • go
  • Related