首页 > 解决方案 > 如何在 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

那么我怎样才能找出未编组对象的长度呢?

标签: gomarshallingunmarshalling

解决方案


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)

推荐阅读