go语言中的不规则json-创新互联
json.Unmarshal 操作对象是一个 []byte,也就意味着被处理的JSON要全部加载到内存。

如果有一个加载完的JSON使用json.Unmarshal会快一些。
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解析的详细内容,更多请关注创新互联其它相关文章!
当前文章:go语言中的不规则json-创新互联
分享路径:http://www.scyingshan.cn/article/dogcsh.html


咨询
建站咨询
