In my Go code, I have multidimensional slices of string
input := [][]string{
{"foods", "food by cooking technique", "baked food"},
{"foods", "food by cooking technique", "baked beans"},
{"foods", "food by type", "dried food"},
{"drinks", "hot drinks", "tea"},
{"drinks", "hot drinks", "herbal tea"},
{"drinks", "cold drinks", "ice cream drinks"},
}
how to convert to json so that the resulting print output is as expected. maybe with recursive
{
"data": [
{
"name": "foods",
"data": [
{
"name": "food by cooking technique",
"data": [
{ "name": "baked food" },
{ "name": "baked beans" }
]
},
{
"name": "food by type",
"data": [
{ "name": "dried food" }
]
}
]
},
{
"name": "drinks",
"data": [
{
"name": "hot drinks",
"data": [
{ "name": "tea" },
{ "name": "herbal tea" }
]
},
{
"name": "cold drinks",
"data": [
{ "name": "ice cream drinks" }
]
}
]
}
]
}
still haven't come up with an idea regarding this, thanks for your help
CodePudding user response:
Not fast, but an understandable approach:
package main
import (
"encoding/json"
"log"
)
type mapStruct struct {
Data map[string]*mapStruct
}
type dataStruct struct {
Name string `json:"name,omitempty"`
Data []*dataStruct `json:"data,omitempty"`
}
func main() {
input := [][]string{
{"foods", "food by cooking technique", "baked food"},
{"foods", "food by cooking technique", "baked beans"},
{"foods", "food by type", "dried food"},
{"drinks", "hot drinks", "tea"},
{"drinks", "hot drinks", "herbal tea"},
{"drinks", "cold drinks", "ice cream drinks"},
}
data := &mapStruct{}
for _, v := range input {
temp := data
for _, vv := range v {
if temp.Data == nil {
temp.Data = map[string]*mapStruct{}
}
if _, ok := temp.Data[vv]; !ok {
temp.Data[vv] = &mapStruct{}
}
temp = temp.Data[vv]
}
}
output := &dataStruct{}
fun(output, data)
bts, err := json.MarshalIndent(output, "", "\t")
if err != nil {
log.Println(err)
return
}
log.Println(string(bts))
}
func fun(d *dataStruct, m *mapStruct) {
for k, v := range m.Data {
d.Data = append(d.Data, &dataStruct{})
d.Data[len(d.Data)-1].Name = k
fun(d.Data[len(d.Data)-1], v)
}
}