亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang多維切片成預期的輸出字符串json

Golang多維切片成預期的輸出字符串json

Go
Cats萌萌 2022-12-26 16:50:41
在我的 Go 代碼中,我有字符串的多維切片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"},}如何轉換為 json 以便生成的打印輸出符合預期。也許遞歸{    "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" }            ]          }        ]      }    ]}還沒有想出這方面的想法,感謝您的幫助
查看完整描述

1 回答

?
蕪湖不蕪

TA貢獻1796條經驗 獲得超7個贊

速度不快,但可以理解的方法:


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)

    }

}


查看完整回答
反對 回復 2022-12-26
  • 1 回答
  • 0 關注
  • 109 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號