JSONx Complete Guide - zhoudm1743/go-util GitHub Wiki

JSONx 是 Go-Util 的高性能 JSON 操作独立包,专为现代 Go 开发而设计。

🚀 特性亮点

  • 🔥 极致性能: 支持 200 层嵌套深度,5000 对象 0.01 秒处理
  • 🎯 链式调用: 流畅的 API 设计,支持方法链
  • 🛡️ 类型安全: 内置类型检查和转换
  • 📦 零依赖: 只使用 Go 标准库
  • 🔧 深度路径: 支持 user.profile.settings.theme 形式访问

📦 安装

go get github.com/zhoudm1743/go-util/jsonx

⚡ 快速开始

import "github.com/zhoudm1743/go-util/jsonx"

// 解析 JSON
j := jsonx.Parse(`{"name": "张三", "age": 25}`)
name := j.Get("name").String()  // "张三"
age := j.Get("age").Int()       // 25

// 创建 JSON
user := jsonx.Object().
    Set("name", "李四").
    Set("age", 30).
    Set("profile.city", "北京")

🎯 核心功能

1. 基础操作

创建 JSON 对象

// 空对象
obj := jsonx.Object()

// 空数组
arr := jsonx.Array()

// 从字符串解析
j := jsonx.Parse(`{"users": [{"name": "Alice"}, {"name": "Bob"}]}`)

// 从 map 创建
data := map[string]interface{}{
    "name": "张三",
    "age":  25,
}
j := jsonx.FromMap(data)

数据获取

j := jsonx.Parse(`{
    "user": {
        "name": "张三",
        "age": 25,
        "active": true,
        "scores": [85, 90, 78]
    }
}`)

// 基础获取
name := j.Get("user.name").String()     // "张三"
age := j.Get("user.age").Int()          // 25
active := j.Get("user.active").Bool()   // true

// 数组获取
firstScore := j.Get("user.scores.0").Int()  // 85

// 类型检查
if j.Get("user.name").IsString() {
    fmt.Println("Name is a string")
}

2. 深度路径操作

JSONx 支持强大的路径操作,可以轻松处理复杂的嵌套结构:

j := jsonx.Object()

// 深度设置 - 自动创建中间路径
j.Set("user.profile.personal.name", "张三")
j.Set("user.profile.contact.emails.0", "[email protected]")
j.Set("user.settings.theme.color", "dark")
j.Set("user.permissions.admin.level", 5)

// 深度获取
name := j.Get("user.profile.personal.name").String()
email := j.Get("user.profile.contact.emails.0").String()

// 路径存在性检查
if j.Has("user.settings.theme") {
    theme := j.Get("user.settings.theme.color").String()
}

// 删除路径
j.Delete("user.permissions.admin")

3. 数组操作

// 创建数组
arr := jsonx.Array().
    Append("Alice").
    Append("Bob").
    Append("Charlie")

// 索引访问
first := arr.Index(0).String()  // "Alice"
length := arr.Length()          // 3

// 数组修改
arr.Remove(1)  // 移除 "Bob"
arr.Prepend("Dave")  // 在开头添加

// 批量操作
users := jsonx.Array()
for i := 0; i < 5; i++ {
    user := jsonx.Object().
        Set("id", i).
        Set("name", fmt.Sprintf("User_%d", i))
    users.Append(user.ToInterface())
}

4. 函数式编程

numbers := jsonx.QuickArray(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

// 过滤偶数
evens := numbers.Filter(func(key string, value *jsonx.JSON) bool {
    return value.Int()%2 == 0
})

// 映射转换
doubled := evens.Map(func(key string, value *jsonx.JSON) interface{} {
    return value.Int() * 2
})

// 遍历处理
users.ForEach(func(key string, user *jsonx.JSON) bool {
    fmt.Printf("User: %s\n", user.Get("name").String())
    return true  // 继续遍历
})

🛠️ 构建器模式

对象构建器

user := jsonx.NewBuilder().
    AddString("name", "王五").
    AddInt("age", 28).
    AddBool("verified", true).
    AddFloat("score", 95.5).
    AddObject("address", jsonx.NewBuilder().
        AddString("city", "上海").
        AddString("district", "浦东新区").
        AddString("street", "世纪大道1000号").
        Build()).
    AddArray("hobbies", jsonx.NewArrayBuilder().
        AppendString("编程").
        AppendString("阅读").
        AppendString("旅行").
        Build()).
    Build()

数组构建器

products := jsonx.NewArrayBuilder().
    AppendObject(jsonx.NewBuilder().
        AddString("name", "笔记本电脑").
        AddFloat("price", 5999.99).
        AddInt("stock", 50).
        Build()).
    AppendObject(jsonx.NewBuilder().
        AddString("name", "无线鼠标").
        AddFloat("price", 199.99).
        AddInt("stock", 200).
        Build()).
    Build()

模板构建器

template := jsonx.NewTemplate(`{
    "user": {
        "name": "{{name}}",
        "age": {{age}},
        "city": "{{city}}"
    },
    "timestamp": "{{timestamp}}"
}`)

result := template.
    Set("name", "赵六").
    Set("age", 32).
    Set("city", "深圳").
    Set("timestamp", time.Now().Format(time.RFC3339)).
    Build()

🎪 高级功能

1. 扁平化和展开

nested := jsonx.QuickObject(map[string]interface{}{
    "user": map[string]interface{}{
        "profile": map[string]interface{}{
            "name": "张三",
            "age":  30,
        },
        "settings": map[string]interface{}{
            "theme": "dark",
            "lang":  "zh-CN",
        },
    },
})

// 扁平化
flattened := jsonx.Flatten(nested)
// 结果: {"user.profile.name": "张三", "user.profile.age": 30, ...}

// 恢复嵌套结构
unflattened := jsonx.Unflatten(flattened)

2. 对象合并

obj1 := jsonx.QuickObject(map[string]interface{}{
    "name": "张三",
    "age":  25,
    "city": "北京",
})

obj2 := jsonx.QuickObject(map[string]interface{}{
    "age":   30,  // 会覆盖
    "email": "[email protected]",  // 新增
})

// 浅合并
merged := jsonx.Merge(obj1, obj2)

// 深度合并
deepMerged := jsonx.DeepMerge(obj1, obj2)

3. 字段选择和排除

user := jsonx.QuickObject(map[string]interface{}{
    "id":       1,
    "name":     "张三",
    "email":    "[email protected]",
    "password": "secret123",
    "token":    "abc123xyz",
    "profile": map[string]interface{}{
        "age":  25,
        "city": "北京",
    },
})

// 只选择特定字段
public := jsonx.Pick(user, "id", "name", "email", "profile")

// 排除敏感字段
safe := jsonx.Omit(user, "password", "token")

4. 数据转换

// 结构体转 JSON
type User struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}

user := User{Name: "张三", Age: 25, Email: "[email protected]"}
j := jsonx.FromStruct(user)

// JSON 转结构体
var userStruct User
err := j.ToStruct(&userStruct)

// 转换为其他格式
jsonStr, _ := j.ToJSON()          // 紧凑 JSON
prettyJSON, _ := j.ToPrettyJSON() // 格式化 JSON
data := j.ToMap()                 // map[string]interface{}
slice := j.ToSlice()              // []interface{}

🔧 实用工具

JSON 验证和格式化

// 验证 JSON 字符串
valid := jsonx.IsValid(`{"name": "test"}`)  // true

// 格式化 JSON
pretty, _ := jsonx.Pretty(`{"name":"test","age":25}`)
/* 结果:
{
  "name": "test",
  "age": 25
}
*/

// 压缩 JSON
minified := jsonx.Minify(prettyJSON)  // {"name":"test","age":25}

信息获取

j := jsonx.Parse(complexJSON)

// 获取大小(字节数)
size := jsonx.Size(j)

// 获取深度
depth := jsonx.Depth(j)

// 获取类型
jsonType := jsonx.GetType(j)  // "object", "array", "string", etc.

Schema 验证

schema := &jsonx.Schema{
    Type: "object",
    Properties: map[string]*jsonx.Schema{
        "name": {Type: "string", Required: true},
        "age":  {Type: "number", Required: true},
        "email": {Type: "string", Required: false},
    },
}

user := jsonx.QuickObject(map[string]interface{}{
    "name": "张三",
    "age":  25,
})

errors := schema.Validate(user)
if len(errors) == 0 {
    fmt.Println("验证通过")
}

⚡ 性能优化

1. 零拷贝操作

JSONx 内部使用 unsafe 包进行零拷贝字符串转换:

// 内部优化 - 用户无需关心
func bytesToString(b []byte) string {
    return *(*string)(unsafe.Pointer(&b))
}

func stringToBytes(s string) []byte {
    return *(*[]byte)(unsafe.Pointer(&s))
}

2. 路径缓存

对于频繁访问的路径,JSONx 会自动缓存解析结果:

j := jsonx.Parse(largeJSON)

// 首次访问会解析路径
value1 := j.Get("deeply.nested.path.to.value")

// 后续访问使用缓存
value2 := j.Get("deeply.nested.path.to.value")  // 更快

3. 批量操作

// 批量设置 - 更高效
builder := jsonx.NewBuilder()
data := map[string]interface{}{
    "name":  "张三",
    "age":   25,
    "email": "[email protected]",
}
builder.AddMany(data)

// 批量追加 - 数组操作
arr := jsonx.Array()
values := []interface{}{"A", "B", "C", "D", "E"}
arr.AppendMany(values)

📊 性能基准

基于我们的测试结果:

深度嵌套测试 (200层):     ✅ 毫秒级完成
大数组处理 (5000对象):    ✅ 0.01秒完成  
序列化 (13万字符):       ✅ < 1毫秒
复杂路径解析:           ✅ O(1) 查找
内存使用:              ✅ 零拷贝优化

🔍 故障排除

常见错误

// 错误:访问不存在的路径
value := j.Get("nonexistent.path").String()  // 返回空字符串

// 正确:检查路径是否存在
if j.Has("user.profile.name") {
    name := j.Get("user.profile.name").String()
}

// 错误:类型不匹配
number := j.Get("name").Int()  // name 是字符串,返回 0

// 正确:类型检查
if j.Get("age").IsNumber() {
    age := j.Get("age").Int()
}

错误处理

j := jsonx.Parse(invalidJSON)
if j.Error() != nil {
    fmt.Printf("解析错误: %v", j.Error())
}

// 链式调用中的错误会传播
result := j.Set("key", "value").Get("key").String()
if j.Error() != nil {
    fmt.Printf("操作错误: %v", j.Error())
}

🎯 最佳实践

1. 错误处理

// 推荐:显式错误检查
j := jsonx.Parse(jsonString)
if j.Error() != nil {
    return fmt.Errorf("JSON 解析失败: %w", j.Error())
}

// 推荐:路径验证
if !j.Has("user.profile") {
    return errors.New("用户配置信息不存在")
}

2. 性能优化

// 推荐:复用 JSON 对象
j := jsonx.Object()
for i := 0; i < 1000; i++ {
    j.Set(fmt.Sprintf("item_%d", i), i)
}

// 避免:频繁创建对象
for i := 0; i < 1000; i++ {
    j := jsonx.Object().Set("value", i)  // 低效
}

3. 内存管理

// 推荐:及时释放大对象
largeJSON := jsonx.Parse(hugeMb.String())
processData(largeJSON)
largeJSON = nil  // 显式释放引用

🔗 相关资源

💬 获取帮助