sonic 序列化和反序列化
import "github.com/bytedance/sonic" var data YourSchema output, err := sonic.Marshal(&data) err := sonic.Unmarshal(output, &data) data := []byte(`{ "person": { "name": { "first": "Leonid", "last": "Bugaev", "fullName": "Leonid Bugaev" }, "github": { "handle": "buger", "aa": 109 }, "avatars": [ { "url": "456", "type": "thumbnail" }, { "url": "123", "type": "ccc" } ] }, "company": { "name": "Acme" } }`) r, _ := sonic.Get(data, "person", "name", "fullName") fmt.Println(r.Raw()) //输出带引号 r1, _ := sonic.GetFromString(string(data), "person", "name", "fullName") fmt.Println(r1.String()) //不带引号 r2, _ := sonic.GetFromString(string(data)) s, _ := r2.GetByPath("person", "github").Map() fmt.Println(s) r3, _ := sonic.Get(data, "person", "avatars") r4, _ := r3.Array() for _, v := range r4 { v1 := v.(map[string]interface{}) fmt.Println(v1["url"]) }
解析支持循环效率高,支持搜索,不支持序列化
"github.com/buger/jsonparser"
data := []byte(`{
"person": {
"name": {
"first": "Leonid",
"last": "Bugaev",
"fullName": "Leonid Bugaev"
},
"github": {
"handle": "buger",
"followers": 109
},
"avatars": [
{ "url": "https://avatars1.githubusercontent.com/u/14009?v=3&s=460", "type": "thumbnail" }
]
},
"company": {
"name": "Acme"
}
}`)
jsonparser.Get(data, "person", "name", "fullName")
jsonparser.GetInt(data, "person", "github", "followers")
jsonparser.Get(data, "company")
var size int64
if value, err := jsonparser.GetInt(data, "company", "size"); err == nil {
size = value
}
jsonparser.ArrayEach(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
fmt.Println(jsonparser.Get(value, "url"))
}, "person", "avatars")
jsonparser.GetString(data, "person", "avatars", "[0]", "url")
jsonparser.ObjectEach(data, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
fmt.Printf("Key: '%s'\n Value: '%s'\n Type: %s\n", string(key), string(value), dataType)
return nil
}, "person", "name")
paths := [][]string{
[]string{"person", "name", "fullName"},
[]string{"person", "avatars", "[0]", "url"},
[]string{"company", "url"},
}
jsonparser.EachKey(data, func(idx int, value []byte, vt jsonparser.ValueType, err error){
switch idx {
case 0: // []string{"person", "name", "fullName"}
case 1: // []string{"person", "avatars", "[0]", "url"}
case 2: // []string{"company", "url"},
}
}, paths...)
文档更新时间: 2024-10-22 04:24 作者:Yoby