Go 和 PHP 通讯是痛苦的,PHP 这个神奇的 json ,各类奇奇怪怪的 json 都能生成出来,若是一开始就奇怪直接用interface也就算了,最可怕那种是类型会变。html
在用 Go 重构 PHP 项目的时候,两个项目每每会共享存储,咱们在生成缓存的时候,也常常把数据转成 json 去存储。git
我大 PHP 生成 json 有这么两个另 Go 崩溃的事情,一个是 int 和 string 的不肯定,第二个就是 PHP array是空的时候,序列化出来是[],可是不为空的时候,序列化出来的是{"key":"value"}。 可是 jsoniter (https://github.com/json-iterator/go、http://jsoniter.com/go-tips.cn.html)对能够作模糊转换,省了不少事情。github
看个例子json
package main import ( "fmt" "github.com/json-iterator/go" "github.com/json-iterator/go/extra" ) func main() { extra.RegisterFuzzyDecoders() var i int var json = jsoniter.ConfigCompatibleWithStandardLibrary json.Unmarshal([]byte(`"1"`), &i) fmt.Printf("我是int %d\n",i) var s string json.Unmarshal([]byte(`"1"`), &s) fmt.Printf("我是string %s\n",s) var m map[string]interface{} jsoniter.UnmarshalFromString(`{}`, &m) fmt.Printf("我是map %s\n",m) return }
结果缓存
我是int 1 我是string 1 我是map map[]
若是没有 jsoniter ,断言写到手软也就算了,程序来几个panic,case study 写到手软才最惨。架构
固然了 jsoniter 也不是万能的,它也仅仅能处理这两种比较常见的,遇到其余奇葩 json 估计只能断言、switch v.(type) case 写到手软了。code
更多架构、PHP、GO相关踩坑实践技巧请关注个人公众号:PHP架构师 htm