Is there any convenient way to get JSON element without type assertion?

纵饮孤独 提交于 2019-12-02 15:05:45

If you model your JSON object with a struct and you unmarshal into a value of that, then you don't need those ugly indices and type assertions, you can simply refer to struct fields.
Note that you don't have to be afraid of the response being complex, you only need to model the parts you intend to use. E.g. if the response is an object with a hundred fields but you only need 2, then create a struct containing only those 2 fields.

If you don't want to model your JSON object (or can't because it's dynamic), then you may write a general utility function which gets a value based on the path (series of map keys and slice indices), which you can see in this answer: Taking a JSON string, unmarshaling it into a map[string]interface{}, editing, and marshaling it into a []byte seems more complicated then it should be

And last you may use 3rd party libs which already contain this helper functionality, such as https://github.com/icza/dyno (disclosure: I'm the author).

Using github.com/icza/dyno, it would look like this:

value, err := dyno.Get(response, "body", 4, "data", "uid")

As per icza you can create struct for JSON object. But in case you are getting JSON structure you don't know from start. Then you can create a dynamic parsing using reflections for interface which will be a recursive function to parse JSON data.

func main(){
    var data interface{}
    err := json.Unmarshal([]bytes(file.json), &data)
    if err != nil {
        panic(err)
    }
    var itemData map[string]interface{}
    itemsMap := data.(map[string]interface{})
    jsonParsedObject := interate(itemsMap)  
    log.Println(jsonParsedObject)  
}

func iterate(data interface{}) interface{} {
    if reflect.ValueOf(data).Kind() == reflect.Slice {
        d := reflect.ValueOf(data)
        tmpData := make([]interface{}, d.Len())
        returnSlice := make([]interface{}, d.Len())
        for i := 0; i < d.Len(); i++ {
            tmpData[i] = d.Index(i).Interface()
        }
        for i, v := range tmpData {
            returnSlice[i] = iterate(v)
        }
        return returnSlice
    } else if reflect.ValueOf(data).Kind() == reflect.Map {
        d := reflect.ValueOf(data)
        tmpData := make(map[string]interface{})
        for _, k := range d.MapKeys() {
            typeOfValue := reflect.TypeOf(d.MapIndex(k).Interface()).Kind()
            if typeOfValue == reflect.Map || typeOfValue == reflect.Slice {
                tmpData[k.String()] = iterate(d.MapIndex(k).Interface())
            } else {
                tmpData[k.String()] = d.MapIndex(k).Interface()
            }
        }
        return tmpData
    }
    return data
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!