I got log data source looks like:
{"LogtypeA":{"content":"listen_logs":[{"useful_key1":val1,"useful_key2":val2},{"useful_key1":val1}]}}
Then I use simplejson to parse them. The value of listen_logs is a slice that contain at least one map. The code is:
for _, v := range js.Get("LogTypeA").Get("content").Get("listen_logs").MustArray() {
_obj := reflect.ValueOf(v)
fmt.Println(_obj.Kind())
}
If I replace MustArray()
with Array()
, it will report incorrect variable and constant declarations. Using reflect module I will find that the _obj.Kind()
is map, but I can't use any indexing method to get values from v
such as:
_val1 := v["useful_key1"]
or
for i, v := range v {...}
Because type interface{}
does not support indexing. So how should I extract those useful keyX from those logs?
You need to perform a type assertion on the resulting map:
new_v := v.(map[string]interface{})
_val1 := new_v["useful_key1"]
Or, if you're not sure it will be a map:
new_v, ok := v.(map[string]interface{})
if ok {
// it was a map from strings to something
_val1 := new_v["useful_key1"]
} else {
print("Could not interpret v as a map.")
}
Since it's initially an empty interface, i.e. interface{}
, that means it can be any type. So, you need to specify that you want to treat it as a map before trying to access the items.