golang json and slices of interface

前端 未结 2 1118
挽巷
挽巷 2021-01-24 12:59

I am having trouble iterating over slices of interfaces that contain slices of interfaces.

This problem has arisen through attempting to work with an API call which retu

2条回答
  •  攒了一身酷
    2021-01-24 13:35

    You can add a switch case which is checking the type of interface for slice of interfaces and then run the same function as recursive until whole json is parsed.

    output := make(map[string]interface{})
    err = json.Unmarshal(body, &output)
    
    fmt.Println(err)
    identify(output)
    
    return err
    }
    
    func identify(output map[string]interface{}) {
        fmt.Printf("%T", output)
        for a, b := range output {
            switch bb := b.(type) {
            case string:
                fmt.Println("This is a string")
            case float64:
                fmt.Println("this is a float")
            case []interface{}:
            // Access the values in the JSON object and place them in an Item
            for _, itemValue := range jsonObj {
                fmt.Printf("%v is an interface\n", itemValue)
                identify(itemValue.(map[string]interface{}))
            }
            default:
                return
            }
        }
    }
    

    There can be deep nested json. We just needs to create options for each case until json is completely parsed.

提交回复
热议问题