Issues Creating JSON using Struct with nested []struct

Hi,

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:

{"category":"xyz",
 "tags":[{"href":"/this/is/a/test/1"},{"href":"/this/is/a/test/2"},{"href":"/this/is/a/test/3"},{"href":"/this/is/a/test/4"}],
  "iface":[{"name":"eth0","address":"192.168.10.1"},{"name":"eth2","address":"10.10.10.1"}]}

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",
        //    
        //},
    }

        fmt.Println(c)
}

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: https://play.golang.org/p/nZi53v_b-y

Thanks in advance,
Rob

OK… Figured it out…

package main

import (
    "encoding/json"
    "fmt"
)

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"}
    all.AddItem(label)

    label2 := Label{Data: "/aaa/bbb/ccc"}
    all.AddItem(label2)

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

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

https://play.golang.org/p/F-tJcweuFK

1 Like

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