简体   繁体   中英

How to Add a field to struct golang using JEN package where fields depend on JSON

Looping through the Json and getting the "name" field with tags and then adding it into a block of struct. Required output after code generation

var queryOutput [][]struct {
        product_name string `db:"product_name" json:"product_name"`
        category     string `db:"category" json:"category"`
        category2    string `db:"category2" json:"category2"`
    }
for _, yaxis := range YAxisColumn {
        columns := yaxis.(map[string]interface{})
        columnName := columns["name"].(string)
        c:= jen.Id(utils.GetFormattedName(columnName)).Int().Tag(map[string]string{
            "json": GetFormattedName(columnName),
            "db":   GetFormattedName(columnName),
        }),
    }

Struct in which to add the Yaxis columns fields ie name

return jen.Func().Id(serviceName).Params().Parens(
        jen.List(jen.Interface(), jen.Error()),
    ).Block(
        jen.Var().Id("queryOutput").Op("[][]").Struct(
            jen.Id(utils.GetFormattedName(XAxisColumn)).String().Tag(map[string]string{
                "json": utils.GetFormattedName(XAxisColumn),
                "db":   utils.GetFormattedName(XAxisColumn),
            }),
),

JSON

"yAxisColumn" : [
                            {
                                "name": "category",
                                "color": ""
                            },
                            {
                                "name": "category2",
                                 "color":""
                            }
],

Use a function named as StructFunc in jen package.

Output after using

jen.Var().Id("queryOutput").Op("[]").StructFunc(
            func(g *jen.Group) {
                g.Add(jen.Id(utils.GetCamelCaseName(XAxisColumn)).String().Tag(map[string]string{
                    "json": utils.GetFormattedName(XAxisColumn),
                    "db":   utils.GetFormattedName(XAxisColumn),
                }))
                for _, yaxis := range YAxisColumn {
                    columns := yaxis.(map[string]interface{})
                    columnName := columns["name"].(string)
                    c := jen.Id(utils.GetCamelCaseName(columnName)).Int().Tag(map[string]string{
                        "json": utils.GetFormattedName(columnName),
                        "db":   utils.GetFormattedName(columnName),
                    })
                    g.Add(c)
                }
            },
        ),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM