如何用buger/jsonparser的EachKey提取JSON Schema中attributes的键
使用
buger/jsonparser 提取JSON指定节点的所有键 针对给定JSON的实现代码
下面是直接满足需求的Go代码,从你提供的JSON结构中提取provider.block.attributes下的所有键:
package main import ( "fmt" "github.com/buger/jsonparser" ) func main() { jsonData := []byte(`{ "provider": { "version": 0, "block": { "attributes": { "access_approval_custom_endpoint": { "type": "string", "description_kind": "plain", "optional": true }, "access_approval_adhoc": { "type": "string", "description_kind": "plain", "optional": true } } } } }`) var attrKeys []string // 先定位到attributes节点的字节数据 attrData, _, _, err := jsonparser.Get(jsonData, "provider", "block", "attributes") if err != nil { fmt.Printf("找不到attributes节点: %v\n", err) return } // 遍历attributes下的所有键值对,收集键名 err = jsonparser.ObjectEach(attrData, func(key []byte, _ []byte, _ jsonparser.ValueType, _ int) error { attrKeys = append(attrKeys, string(key)) return nil }) if err != nil { fmt.Printf("遍历attributes失败: %v\n", err) return } fmt.Println("提取到的键列表:", attrKeys) }
运行后输出:提取到的键列表: [access_approval_custom_endpoint access_approval_adhoc]
关键逻辑说明
- 定位目标节点:用
jsonparser.Get传入路径provider.block.attributes,直接拿到该节点的原始字节数据,避免遍历整个大JSON。 - 遍历键名:调用
jsonparser.ObjectEach遍历目标节点的所有子项,回调函数中把字节类型的键转成字符串,存入切片。
buger/jsonparser 常用方法示例
1. 快速获取指定路径的值
// 获取provider的version字段(整数类型) version, err := jsonparser.GetInt(jsonData, "provider", "version") if err == nil { fmt.Println("version值:", version) // 输出: version值: 0 } // 获取某个attribute的type字段(字符串类型) attrType, err := jsonparser.GetString(jsonData, "provider", "block", "attributes", "access_approval_custom_endpoint", "type") if err == nil { fmt.Println("type值:", attrType) // 输出: type值: string }
2. 使用EachKey处理指定键
EachKey适合提前知道要处理的键名时使用,按顺序返回对应键的值:
// 批量获取指定的两个attribute的optional字段 err = jsonparser.EachKey(jsonData, func(idx int, value []byte, vt jsonparser.ValueType, err error) { if err != nil { return } // 解析布尔值 optional, _ := jsonparser.ParseBoolean(value) fmt.Printf("第%d个键的optional值: %t\n", idx+1, optional) }, "provider", "block", "attributes", "access_approval_custom_endpoint", "optional", "provider", "block", "attributes", "access_approval_adhoc", "optional")
3. 判断值的类型
遍历节点时,可以通过ValueType判断当前值的类型:
jsonparser.ObjectEach(attrData, func(key []byte, value []byte, dataType jsonparser.ValueType, _ int) error { switch dataType { case jsonparser.Object: fmt.Printf("%s 是对象类型\n", key) case jsonparser.String: fmt.Printf("%s 是字符串类型\n", key) } return nil })
内容的提问来源于stack exchange,提问作者Mohammed Saaduddin Ansari
相关产品推荐
相关产品推荐

