Hacker News new | past | comments | ask | show | jobs | submit login

I think the solution posed to you is at least much better than what your comment thread started with: defining the entire JSON structure with Go types. Actually, I think it's a lot better. Personally, I'd probably stop there---even if I were prototyping.

But, at your insistence, we can keep digging. It's easy to write a polymorphic function that arbitrarily picks out values from a Go `interface{}` value.

    func lookup(v interface{}, keys ...string) interface{} {
    	switch len(keys) {
    	case 0: return v
    	default:
    		dict, ok := v.(map[string]interface{})
    		if !ok {
    			panic(fmt.Sprintf("%T is not a dictionary", v))
    		}
    		return lookup(dict[keys[0]], keys[1:]...)
    	}
    }
And then we can use it like you would in Python:

    lookup(response, "level_one", "level_two", "eventual_value")
This doesn't completely remove the burden of type asserting (unfortunate), but it at least makes nested lookups much easier. Arguably, the nested lookups are probably where the type asserts hurt the most.

Full example: http://play.golang.org/p/4tWtqGRgU6




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: