go多维map只能 for range 循环取嘛

关于go多维map取值的方法

举个例子🌰
urls :="http://adminapi.test/api/captcha"
    data := url.Values{"app_id":{"238b2213-a8ca-42d8-8eab-1f1db3c50ed6"}, "mobile_tel":{"13794227450"}}
    body := strings.NewReader(data.Encode())
    resp,err := http.Post(urls,"application/x-www-form-urlencoded",body)

    if err!=nil{
        fmt.Println(err)
    }

    defer resp.Body.Close()

    bodyC, _ := ioutil.ReadAll(resp.Body)

    jsonMap := helpler.JsonToMap(bodyC)

    err = json.Unmarshal(bodyC, &jsonMap)
    if err != nil {
        fmt.Println(err)
        return
    }
    datas := jsonMap["data"]
    fmt.Println(datas)

map结构

map[captcha:map[img:xxx key:$2y$10$TA9H/rHeYj1ZkRgsDZtSjeS8nvA.94wHQ.0AJjuGmu1Ysv510H/u. sensitive:false]]

对应的json字符串

{
    "code":200,
    "message":"success",
    "data":{
        "captcha":{
            "sensitive":false,
            "key":"$2y$10$mAo\/\/MSADix5j6HaqFIqBuQ5TbEVBhkexRzCiExj4NM4nLUkZYf92",
            "img":"xxx"
        }
    }
}

我想取 key的数据

map
不成大牛,不改個簽
讨论数量: 5
pardon110

有第三方库,类似xpath或css解析器,通过键解析到具体的值

2年前 评论

还是推荐自行定义结构体来接收来自 API 数据,高性能。

map 不推荐用在这种情况。

比如,只是需要用到 data 中的 captcha,那么可以定义结构体:

type Response struct {
    // Code    int    `json:"code"`
    // Message string `json:"message"`
    Data    Data   `json:"data"`
}

type Data struct {
    Captcha Captcha `json:"captcha"`
} 

type Captcha struct {
    Key       string `json:"key"`
    // Img       string `json:"img"`
    // Sensitive bool   `json:"senstive"`
}

然后使用 data 结构体接收 json:

    j := `
    {
        "code":200,
        "message":"success",
        "data":{
            "captcha":{
                "sensitive":false,
                "key":"$2y$10$mAo\/\/MSADix5j6HaqFIqBuQ5TbEVBhkexRzCiExj4NM4nLUkZYf92",
                "img":"xxx"
            }
        }
    }`

    resp := new(Response)

    err := json.Unmarshal([]byte(j), resp)
    if err != nil {
        fmt.Printf("err:%s\n", err.Error())
    }
    fmt.Println("Response: \t", j)
    fmt.Printf("Response.Data.Captcha.Key = %s\n", resp.Data.Captcha.Key)
2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!