Oh, Tomahawk uses Go now? Nice :)
You could call Unmarshal like this:
var t interface{}
json.Unmarshal(str, &t)
Now t is a newly allocated map[string]interface{}, and you can test
for a field's presence with something like:
tm := t.(map[string]interface{})
for k := range fieldsicareabout {
_, present := tm[k]
if present {
// yay
} else {
// boo
}
}
I think reflect is what you want and the Value.Field* methods to get the Value.
Yup: http://play.golang.org/p/5Squ3mr7K7
On Mon, Aug 20, 2012 at 2:18 PM, <swh...@ngmoco.com> wrote:
> I think the "Ptr" Kind is what you'll get if it's a pointer to any type
> except the special ones listed. I did not try it though, so you should
> confirm. If your struct is going to contain any non-pointers then you
> should check the Kind before checking for Nil to avoid panics.
On 20 August 2012 22:21, Jeff Mitchell <je...@tomahawk-player.org> wrote:I'm not sure that Pointer is the right method to use there,
> For posterity/future questioners' reference, here's my completed function;
> it compiles, although I have not yet tested it:
>
> func checkNils(strct interface{}) bool {
> v := reflect.ValueOf(strct)
> if v.Kind() != reflect.Struct {
> return false
> }
> for i := 0; i < v.NumField(); i++ {
> if v.Field(i).Kind() != reflect.Ptr {
> return false
> }
> if v.Field(0).Pointer() == 0 {
> return false
> }
> }
> return true
> }
and I'm sure you don't want to be using Field(0) in the
second expression there :-)
Also returning false when you find a non-pointer doesn't
seem quite right - if you allow non-pointer fields, it allows
a convenient get-out clause for optional fields.
func checkNils(x interface{}) bool {
v := reflect.ValueOf(x)
if v.Kind() != reflect.Struct {f := v.Field(i)
return false
}
for i := 0; i < v.NumField(); i++ {
if f.Kind() != reflect.Ptr {
continue
}
if f.IsNil() {
return false
}
}
return true
}