Issues Creating JSON using Struct with nested []struct


I’m new to the forum and this is my first post…

Disclaimer: I have done a ton of searches and can’t seem to find what I am looking for. I’m trying to construct a JSON payload based on some data I am parsing from a CSV file. The final output will look something like the following:


Here is what I have as far as code goes:

package main

import "fmt"

type FoobStruct struct {
    Category string `json:"category"`
    Tags []struct {
        Href string `json:"href"`
    } `json:"tags"`
    Iface []struct {
        Name string `json:"name"`
        Address string `json:"address"`
    } `json:"iface"`

func main() {

    c := &FoobStruct{
        Category: "test",
        //Tags: {
        //Href: "addr",


My goal is populate data into HREF and IFACE but can’t figure out how to do this. I have also tried creating a separate struct and am running into the same issue and can’t seem to figure it out. I know I am probably missing something simple however all of the examples I have found don’t contain a struct inside a struct like what I have above. One other thing to mention that is semi-related is that for both fields are optional so they will contain anywhere from 0 or more data points so I’m trying to figure out how to not add empty fields.

Here is the goplayground link:

Thanks in advance,

OK… Figured it out…

package main

import (

type Label struct {
    Data string

type Tags struct {
    Label []Label

func (p *Tags) AddItem(l Label) []Label {
    p.Label = append(p.Label, l)
    return p.Label

type FoobStruct struct {
    Name   string
    Tags []Label

func main() {
    all := Tags{[]Label{}}

    label := Label{Data: "/xxx/yyy/zzz"}

    label2 := Label{Data: "/aaa/bbb/ccc"}

  // Dynamically determine the amount of Tags given 
    foob := "*******"  //  Remove astericks to and run again
    if len(foob) > 0 {
        label3 := Label{Data: foob}

    p := &FoobStruct{Name: "foo", Tags: all.Label, }
    pl, _ := json.Marshal(p)

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.