go - 如何在 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)
推荐阅读
- angular - 我们可以在不使用 GraphQL 的情况下在项目中实施 AWS-Appsync 吗?
- jquery - 阻止某些特定页面中的特定 css 内容
- python - 通过客户端/服务器网络将 5 位整数转换为字节
- php - ErrorException(E_ERROR)试图获取非对象的属性“标题” - Laravel 5.7
- javascript - React:警告:无法对未安装的组件执行 React 状态更新
- angular - 检查后表达式已更改。以前的值:“假”。当前值:“真”
- firebase - Firebase: Sign in with a token
- google-chrome - 如何符号化 chrome 浏览器堆转储来分析内存泄漏
- angular - 使用带有 PrimeNg OverlayPanel 的 ChangeDetectorRef 分离方法
- c# - 如何在指定目录中找到最近修改的文件 - WMI Query