![](https://img.php.cn/upload/article/000/000/029/5df866d32207d633.jpg)
json.Unmarshal 操作对象是一个 []byte,也就意味着被处理的JSON要全部加载到内存。
如果有一个加载完的JSON使用json.Unmarshal会快一些。 (推荐学习:go)
json.Decoder 操作的是一个stream,或者其他实现了io.Reader接口的类型。意味着可以在接收或传输的同时对其进行解析。当处理一组较大数据时无需重新copy整个JSON到内存中。
最好的选择办法如下:
如果数据来自一个io.Reader或者需要从一个stream中读取数据,就选择json.Decoder
如果已经将整个JSON加载到内存中了就使用json.Unmarshal
不定类型的解析
有时候遇到字段不定的JSON,需要一边判断一边解析。如:
t1 := `{"type":"a", id:"aaa"}`t2 := `{"type":"b", id:22222}`
解组到interface{}
可以先统一解组到interface{} 然后判断关键字段再进行后续处理。
type Data struct { Type string `json:"type"` Id interface{} `json:"id"`}func decode(t string) { var x Data err := json.Unmarshal([]byte(t), &x) if err != nil { panic(err) } if x.Type == "a" { fmt.Println(x.Id.(string)) } else { fmt.Println(x.Id.(float64)) //json解析中number默认作为float64解析 } }func main() { t1 := `{"type":"a", "id":"aaa"}` t2 := `{"type":"b", "id":22222}` decode(t1) decode(t2) }
结果
aaa 22222
以上就是golang不规则json解析的详细内容,更多请关注php中文网其它相关文章!
![php中文网最新课程二维码](/static/images/article_wechat2021.jpg?1111)
声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
- 上一篇:golang不定长参数写法
- 下一篇:golang不开发gui吗
网友评论
文明上网理性发言,请遵守 新闻评论服务协议
我要评论