在学习JavaScript时,经常用到的数据类型是JSON,作为JavaScript衍生出来的数据结构,js可以通过encode和decode基础方法来进行对象和JSON的相互转化,而在Golang中同样有相应的包及方法来解析JSON…
类型转换规则:
- bool类型 转换为JSON的Boolean
- 整数,浮点数等数值类型 转换为JSON的Number
- string 转换为JSON的字符串(带””引号)
- struct 转换为JSON的Object,再根据各个成员的类型递归打包
- 数组或切片 转换为JSON的Array
- []byte 会先进行base64编码然后转换为JSON字符串
- map 转换为JSON的Object,key必须是string
- interface{} 按照内部的实际类型进行转换
- nil 转为JSON的null
- channel,func等类型 会返回UnsupportedTypeError
Encode
func Marshal(v interface{}) ([]byte, error)
type ColorGroup struct { |
Decode
func Unmarshal(data []byte, v interface{}) error
var jsonBlob = []byte(`[ |
踩坑
- 由于js里面数值类型为Number,所以当Golang解析JSON时就统一将Number转成了float64
- 结构体的字段必须为大写字母开头才会被打包进JSON里面
- JSON中的
object
会被解析为map[string]interface{}
类型
END