如何获取在 GoLang 中解析 JSON 后的对象的长度?

时间:2024-02-24

浏览:383

作者:佚名

欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《如何获取在 GoLang 中解析 JSON 后的对象的长度?》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!

问题内容

["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 的类型返回 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)

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
首页