```
feat(gjson): 添加JSON解析功能并完善示例程序 新增Parse函数用于解析JSON字符串,支持对象、数组和基础数据类型 完善main.go示例程序,添加Parse使用示例,优化代码格式和注释 ```
This commit is contained in:
parent
43aabcf610
commit
f31549ea24
|
|
@ -2,55 +2,59 @@ package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"git.kingecg.top/kingecg/gjson"
|
"git.kingecg.top/kingecg/gjson"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
fmt.Println("GJson 示例程序")
|
fmt.Println("GJson 示例程序")
|
||||||
|
|
||||||
// 创建JSONObject
|
// 创建JSONObject
|
||||||
obj := gjson.NewJSONObject()
|
obj := gjson.NewJSONObject()
|
||||||
obj.Put("name", gjson.NewJSONString("张三").Value())
|
obj.Put("name", gjson.NewJSONString("张三").Value())
|
||||||
obj.Put("age", gjson.NewJSONNumber(25).Value())
|
obj.Put("age", gjson.NewJSONNumber(25).Value())
|
||||||
obj.Put("student", gjson.NewJSONBool(false).Value())
|
obj.Put("student", gjson.NewJSONBool(false).Value())
|
||||||
|
|
||||||
// 创建嵌套对象
|
// 创建嵌套对象
|
||||||
address := gjson.NewJSONObject()
|
address := gjson.NewJSONObject()
|
||||||
address.Put("city", gjson.NewJSONString("北京").Value())
|
address.Put("city", gjson.NewJSONString("北京").Value())
|
||||||
address.Put("zip", gjson.NewJSONNumber(100000).Value())
|
address.Put("zip", gjson.NewJSONNumber(100000).Value())
|
||||||
obj.Put("address", address.GetData()) // 使用GetData()方法
|
obj.Put("address", address.GetData()) // 使用GetData()方法
|
||||||
|
|
||||||
// 创建数组
|
// 创建数组
|
||||||
arr := gjson.NewJSONArray()
|
arr := gjson.NewJSONArray()
|
||||||
arr.Append(gjson.NewJSONString("item1").Value())
|
arr.Append(gjson.NewJSONString("item1").Value())
|
||||||
arr.Append(gjson.NewJSONNumber(123).Value())
|
arr.Append(gjson.NewJSONNumber(123).Value())
|
||||||
obj.Put("items", arr.GetData()) // 使用GetData()方法
|
obj.Put("items", arr.GetData()) // 使用GetData()方法
|
||||||
|
|
||||||
// 序列化到JSON
|
// 序列化到JSON
|
||||||
jsonStr, _ := obj.ToJSON()
|
jsonStr, _ := obj.ToJSON()
|
||||||
fmt.Printf("JSON对象: %s\n", jsonStr)
|
fmt.Printf("JSON对象: %s\n", jsonStr)
|
||||||
|
|
||||||
// 使用Stringify函数
|
// 使用Stringify函数
|
||||||
stringified, _ := gjson.Stringify(obj)
|
stringified, _ := gjson.Stringify(obj)
|
||||||
fmt.Printf("Stringify结果: %s\n", stringified)
|
fmt.Printf("Stringify结果: %s\n", stringified)
|
||||||
|
|
||||||
|
// Parse
|
||||||
|
parsed, _ := gjson.Parse(jsonStr)
|
||||||
|
fmt.Printf("Parse结果: %v\n", parsed)
|
||||||
// 使用PrettyPrint格式化输出
|
// 使用PrettyPrint格式化输出
|
||||||
pretty, _ := gjson.PrettyPrint(obj)
|
pretty, _ := gjson.PrettyPrint(obj)
|
||||||
fmt.Printf("格式化输出:\n%s\n", pretty)
|
fmt.Printf("格式化输出:\n%s\n", pretty)
|
||||||
|
|
||||||
// 使用Compact函数
|
// 使用Compact函数
|
||||||
compact, _ := gjson.Compact(obj)
|
compact, _ := gjson.Compact(obj)
|
||||||
fmt.Printf("紧凑格式: %s\n", compact)
|
fmt.Printf("紧凑格式: %s\n", compact)
|
||||||
|
|
||||||
// 从JSON字符串创建对象
|
// 从JSON字符串创建对象
|
||||||
newObj := gjson.NewJSONObject()
|
newObj := gjson.NewJSONObject()
|
||||||
newObj.FromJSON(jsonStr)
|
newObj.FromJSON(jsonStr)
|
||||||
|
|
||||||
// 获取属性值
|
// 获取属性值
|
||||||
nameVal, _ := newObj.Get("name")
|
nameVal, _ := newObj.Get("name")
|
||||||
name := gjson.NewJSONString(fmt.Sprintf("%v", nameVal))
|
name := gjson.NewJSONString(fmt.Sprintf("%v", nameVal))
|
||||||
fmt.Printf("姓名: %s\n", name.Value())
|
fmt.Printf("姓名: %s\n", name.Value())
|
||||||
|
|
||||||
// 测试嵌套属性
|
// 测试嵌套属性
|
||||||
addressVal, _ := newObj.Get("address")
|
addressVal, _ := newObj.Get("address")
|
||||||
if addrMap, ok := addressVal.(map[string]interface{}); ok {
|
if addrMap, ok := addressVal.(map[string]interface{}); ok {
|
||||||
|
|
@ -59,66 +63,66 @@ func main() {
|
||||||
fmt.Printf("地址城市: %v\n", cityVal)
|
fmt.Printf("地址城市: %v\n", cityVal)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 使用GetProperty方法
|
// 使用GetProperty方法
|
||||||
defaultValue := gjson.NewJSONString("default")
|
defaultValue := gjson.NewJSONString("default")
|
||||||
propResult, _ := gjson.GetProperty(newObj, "name", defaultValue)
|
propResult, _ := gjson.GetProperty(newObj, "name", defaultValue)
|
||||||
if str, ok := propResult.(*gjson.JSONString); ok {
|
if str, ok := propResult.(*gjson.JSONString); ok {
|
||||||
fmt.Printf("通过GetProperty获取的姓名: %s\n", str.Value())
|
fmt.Printf("通过GetProperty获取的姓名: %s\n", str.Value())
|
||||||
}
|
}
|
||||||
|
|
||||||
propResult2, _ := gjson.GetProperty(newObj, "address.city", defaultValue)
|
propResult2, _ := gjson.GetProperty(newObj, "address.city", defaultValue)
|
||||||
if str, ok := propResult2.(*gjson.JSONString); ok {
|
if str, ok := propResult2.(*gjson.JSONString); ok {
|
||||||
fmt.Printf("通过GetProperty获取的城市: %s\n", str.Value())
|
fmt.Printf("通过GetProperty获取的城市: %s\n", str.Value())
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置属性值
|
// 设置属性值
|
||||||
gjson.SetProperty(newObj, "address.city", gjson.NewJSONString("上海"))
|
gjson.SetProperty(newObj, "address.city", gjson.NewJSONString("上海"))
|
||||||
modifiedProp, _ := gjson.GetProperty(newObj, "address.city", defaultValue)
|
modifiedProp, _ := gjson.GetProperty(newObj, "address.city", defaultValue)
|
||||||
if str, ok := modifiedProp.(*gjson.JSONString); ok {
|
if str, ok := modifiedProp.(*gjson.JSONString); ok {
|
||||||
fmt.Printf("修改后的城市: %s\n", str.Value())
|
fmt.Printf("修改后的城市: %s\n", str.Value())
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建JSONArray并演示其用法
|
// 创建JSONArray并演示其用法
|
||||||
jsonArray := gjson.NewJSONArray()
|
jsonArray := gjson.NewJSONArray()
|
||||||
jsonArray.Append(gjson.NewJSONString("first").Value())
|
jsonArray.Append(gjson.NewJSONString("first").Value())
|
||||||
jsonArray.Append(gjson.NewJSONNumber(42).Value())
|
jsonArray.Append(gjson.NewJSONNumber(42).Value())
|
||||||
|
|
||||||
nestedObj := gjson.NewJSONObject()
|
nestedObj := gjson.NewJSONObject()
|
||||||
nestedObj.Put("nestedProp", gjson.NewJSONString("nestedValue").Value())
|
nestedObj.Put("nestedProp", gjson.NewJSONString("nestedValue").Value())
|
||||||
jsonArray.Append(nestedObj.GetData()) // 使用GetData()方法
|
jsonArray.Append(nestedObj.GetData()) // 使用GetData()方法
|
||||||
|
|
||||||
arrayJson, _ := jsonArray.ToJSON()
|
arrayJson, _ := jsonArray.ToJSON()
|
||||||
fmt.Printf("JSON数组: %s\n", arrayJson)
|
fmt.Printf("JSON数组: %s\n", arrayJson)
|
||||||
|
|
||||||
// 使用Stringify格式化数组
|
// 使用Stringify格式化数组
|
||||||
arrayStringified, _ := gjson.Stringify(jsonArray, " ")
|
arrayStringified, _ := gjson.Stringify(jsonArray, " ")
|
||||||
fmt.Printf("格式化数组:\n%s\n", arrayStringified)
|
fmt.Printf("格式化数组:\n%s\n", arrayStringified)
|
||||||
|
|
||||||
// 访问数组元素
|
// 访问数组元素
|
||||||
firstElement, _ := jsonArray.Get(0)
|
firstElement, _ := jsonArray.Get(0)
|
||||||
fmt.Printf("第一个元素: %v\n", firstElement)
|
fmt.Printf("第一个元素: %v\n", firstElement)
|
||||||
|
|
||||||
// 访问嵌套对象
|
// 访问嵌套对象
|
||||||
nestedValue, _ := gjson.GetProperty(jsonArray, "2.nestedProp", gjson.NewJSONString("default"))
|
nestedValue, _ := gjson.GetProperty(jsonArray, "2.nestedProp", gjson.NewJSONString("default"))
|
||||||
if str, ok := nestedValue.(*gjson.JSONString); ok {
|
if str, ok := nestedValue.(*gjson.JSONString); ok {
|
||||||
fmt.Printf("嵌套对象属性: %s\n", str.Value())
|
fmt.Printf("嵌套对象属性: %s\n", str.Value())
|
||||||
}
|
}
|
||||||
|
|
||||||
// 演示各种值类型的Stringify
|
// 演示各种值类型的Stringify
|
||||||
nullValue := gjson.NewJSONNull()
|
nullValue := gjson.NewJSONNull()
|
||||||
nullStr, _ := gjson.Stringify(nullValue)
|
nullStr, _ := gjson.Stringify(nullValue)
|
||||||
fmt.Printf("空值Stringify: %s\n", nullStr)
|
fmt.Printf("空值Stringify: %s\n", nullStr)
|
||||||
|
|
||||||
boolValue := gjson.NewJSONBool(true)
|
boolValue := gjson.NewJSONBool(true)
|
||||||
boolStr, _ := gjson.Stringify(boolValue)
|
boolStr, _ := gjson.Stringify(boolValue)
|
||||||
fmt.Printf("布尔值Stringify: %s\n", boolStr)
|
fmt.Printf("布尔值Stringify: %s\n", boolStr)
|
||||||
|
|
||||||
numValue := gjson.NewJSONNumber(42.5)
|
numValue := gjson.NewJSONNumber(42.5)
|
||||||
numStr, _ := gjson.Stringify(numValue)
|
numStr, _ := gjson.Stringify(numValue)
|
||||||
fmt.Printf("数字Stringify: %s\n", numStr)
|
fmt.Printf("数字Stringify: %s\n", numStr)
|
||||||
|
|
||||||
strValue := gjson.NewJSONString("hello world")
|
strValue := gjson.NewJSONString("hello world")
|
||||||
strStr, _ := gjson.Stringify(strValue)
|
strStr, _ := gjson.Stringify(strValue)
|
||||||
fmt.Printf("字符串Stringify: %s\n", strStr)
|
fmt.Printf("字符串Stringify: %s\n", strStr)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,81 @@
|
||||||
|
package gjson
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Parse 解析JSON字符串并返回对应的JSONBaseObject
|
||||||
|
func Parse(jsonStr string) (JSONBaseObject, error) {
|
||||||
|
// 去除首尾空白字符
|
||||||
|
trimmed := strings.TrimSpace(jsonStr)
|
||||||
|
|
||||||
|
if len(trimmed) == 0 {
|
||||||
|
return nil, &ParseError{"empty JSON string"}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据第一个非空字符判断是对象还是数组
|
||||||
|
switch trimmed[0] {
|
||||||
|
case '{':
|
||||||
|
// 解析为JSONObject
|
||||||
|
obj := NewJSONObject()
|
||||||
|
err := obj.FromJSON(jsonStr)
|
||||||
|
return obj, err
|
||||||
|
case '[':
|
||||||
|
// 解析为JSONArray
|
||||||
|
arr := NewJSONArray()
|
||||||
|
err := arr.FromJSON(jsonStr)
|
||||||
|
return arr, err
|
||||||
|
default:
|
||||||
|
// 尝试解析为基础类型
|
||||||
|
return parsePrimitiveValue(jsonStr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseError 解析错误
|
||||||
|
type ParseError struct {
|
||||||
|
Message string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *ParseError) Error() string {
|
||||||
|
return "parse error: " + e.Message
|
||||||
|
}
|
||||||
|
|
||||||
|
// parsePrimitiveValue 解析基础值类型
|
||||||
|
func parsePrimitiveValue(jsonStr string) (JSONBaseObject, error) {
|
||||||
|
trimmed := strings.TrimSpace(jsonStr)
|
||||||
|
|
||||||
|
// 检查是否为字符串
|
||||||
|
if len(trimmed) >= 2 && trimmed[0] == '"' && trimmed[len(trimmed)-1] == '"' {
|
||||||
|
// 解析字符串,去除首尾引号
|
||||||
|
var str string
|
||||||
|
err := json.Unmarshal([]byte(jsonStr), &str)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return NewJSONString(str), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否为布尔值
|
||||||
|
if trimmed == "true" {
|
||||||
|
return NewJSONBool(true), nil
|
||||||
|
}
|
||||||
|
if trimmed == "false" {
|
||||||
|
return NewJSONBool(false), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否为null
|
||||||
|
if trimmed == "null" {
|
||||||
|
return NewJSONNull(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 尝试解析为数字
|
||||||
|
var num float64
|
||||||
|
err := json.Unmarshal([]byte(jsonStr), &num)
|
||||||
|
if err == nil {
|
||||||
|
return NewJSONNumber(num), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果都不是,则可能是无效的JSON
|
||||||
|
return nil, &ParseError{"unrecognized JSON value: " + jsonStr}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue