如何在GoLang中找到json.Unmarshalled对象的长度?

问题描述

[“ contexts”]我有以下GoLang代码

1:      unmarshalledBody := make(map[string]interface{})
2:      err = json.Unmarshal(someData,&unmarshalledBody)
3:      fmt.Println(unmarshalledBody["some-key"])
4:      fmt.Println(len(unmarshalledBody["some-key"]))

第3行导致此输出

[map[A:R B:T C:V] map[A:S B:U C:W]]

第4行导致此错误

invalid argument unmarshalledBody (type interface {}) for len

那么我如何找出未编组对象的长度?

解决方法

func len(v类型)int

len内置函数根据其类型返回v的长度:

Array: the number of elements in v.
Pointer to array: the number of elements in *v (even if v is nil).
Slice,or map: the number of elements in v; if v is nil,len(v) is zero.
String: the number of bytes in v.
Channel: the number of elements queued (unread) in the channel buffer;
     if v is nil,len(v) is zero.

https://golang.org/src/builtin/builtin.go?s=5935:5955#L148

建议:

val,ok := unmarshalledBody["some-key"].(type)