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

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

在 map[string]interface{} 的值上輸入 switch to

在 map[string]interface{} 的值上輸入 switch to

Go
慕雪6442864 2023-07-10 15:05:21
問題我面臨著從 json 對象中刪除不需要的數組的問題,例如。僅包含一個元素的數組,該元素不是對象或數組。(沒有數組作為輸入的根)例子在:{"name": [{ "inner": ["test"] }]}通緝:{"name": [{ "inner": "test" }]}方法我從對 a 的值進行簡單的類型切換開始map[string]interface{},并認識到它不會切換到 case []map[string]interface{}。(給出例子)這是我想出的實現。它適用于大多數場景,但不適用于數組中的內部對象。type jsonMap map[string]interface{}type jsonMapList []map[string]interface{}m := jsonMap{}err := json.Unmarshal(s, &m)if err != nil {    panic(err)}res := removeFromObject(m)bytes, err := json.Marshal(res)if err != nil {    panic(err)}result := string(bytes)log.Infof("Parse Result: %s", result)func removeFromObject(in jsonMap) jsonMap {    res := jsonMap{}    for k, v := range in {        switch value := v.(type) {        case jsonMap:            res[k] = removeFromObject(value)        case jsonMapList:            list := []jsonMap{}            for _, entry := range value {                list = append(list, removeFromObject(entry))            }            res[k] = list        case []interface{}:            if len(value) == 1 {                res[k] = value[0]            } else {                res[k] = value            }        default:            res[k] = value        }    }    return res}問題如何將大小寫切換為對象數組,以便我也可以遞歸解析該數組中的對象?
查看完整描述

1 回答

?
LEATH

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

您可以使用此函數刪除不需要的數組。


func removearr(x interface{}) interface{} {

    switch val := x.(type) {

    case map[string]interface{}:

        for k, v := range val {

            val[k] = removearr(v)

        }

        return val

    case []interface{}:

        if len(val) == 1 {

            // remove array only if the value is not an object

            if _, ok := val[0].(map[string]interface{}); !ok {

                return removearr(val[0])

            }

        }


        for i, v := range val {

            val[i] = removearr(v)

        }

        return val

    default:

        return x

    }

}

https://play.golang.com/p/mwo7Y2rJ_lc


查看完整回答
反對 回復 2023-07-10
  • 1 回答
  • 0 關注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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