package main import ( "encoding/json" "fmt" "io/ioutil" "log" "github.com/dave/jennifer/jen" ) type Quote struct { Author string `json:"author"` Book string `json:"book"` Text string `json:"text"` Time string `json:"time"` } func read(p string) (map[string][]Quote, error) { m := map[string][]Quote{} f, err := ioutil.ReadFile(p) if err != nil { return m, fmt.Errorf("could not read json file: %w", err) } if err := json.Unmarshal(f, &m); err != nil { return m, fmt.Errorf("could not unmarshal file: %w", err) } return m, nil } func main() { m, err := read("assets/litdata.json") if err != nil { log.Fatal(err) } f := jen.NewFile("quotes") f.Comment("Code generated by go generate.") f.Comment("nolint: lll") f.Var().Id("FortData").Op("=").Map(jen.String()).Index().Id("Quote").Values(jen.DictFunc(func(d jen.Dict) { for k, v := range m { qs := []jen.Code{} for _, i := range v { qs = append(qs, jen.Id("Quote").Values( jen.Dict{ jen.Id("Author"): jen.Lit(i.Author), jen.Id("Book"): jen.Lit(i.Book), jen.Id("Text"): jen.Lit(i.Text), jen.Id("Time"): jen.Lit(i.Time), }, ), ) } d[jen.Lit(k)] = jen.Index().Id("Quote").Values( qs..., ) } })) f.Type().Id("Quote").Struct( jen.Id("Author").String(), jen.Id("Book").String(), jen.Id("Text").String(), jen.Id("Time").String(), ) if err := f.Save("quotes/quotes.go"); err != nil { log.Fatalf("could not save file: %s", err.Error()) } }