golang json 为map[string] interface{}

json字符串:

{"sn":1,"ls":false,"bg":0,"ed":0,"ws":[{"bg":0,"cw":[{"sc":0,"w":"还"}]},{"bg":0,"cw":[{"sc":0,"w":"有点"}]},{"bg":0,"cw":[{"sc":0,"w":"眼熟"}]}]}

需要将json格式中的w字段取出来,并且拼成结果串进行展示

  1. 从json数组中获取ws
  2. ws是数组,数组元素为object
  3. cw是数组,数组元素为object
  4. w是string
  5. 从cw遍历获取w字段

解析代码:

func RecResultJsonToPlain() {
    var recResult string
    var dat map[string]interface{}
    json.Unmarshal([]byte(json_str), &dat)

    if v, ok := dat["ws"]; ok {
        ws := v.([]interface{})
        for i, wsItem := range ws {
            wsMap := wsItem.(map[string]interface{})
            if vCw, ok := wsMap["cw"]; ok {
                cw := vCw.([]interface{})
                for i, cwItem := range cw {
                    cwItemMap := cwItem.(map[string]interface{})
                    if w, ok := cwItemMap["w"]; ok {
                        recResult = recResult + w.(string)
                    }
                }
            }
        }
    }
    fmt.Println(recResult)
}


你可能感兴趣的:(golang)