feat(gjson): 添加JSON解析功能并完善示例程序

新增Parse函数用于解析JSON字符串,支持对象、数组和基础数据类型
完善main.go示例程序,添加Parse使用示例,优化代码格式和注释
```
This commit is contained in:
kingecg 2026-03-08 16:50:54 +08:00
parent 43aabcf610
commit f31549ea24
2 changed files with 112 additions and 27 deletions

View File

@ -2,6 +2,7 @@ package main
import (
"fmt"
"git.kingecg.top/kingecg/gjson"
)
@ -18,13 +19,13 @@ func main() {
address := gjson.NewJSONObject()
address.Put("city", gjson.NewJSONString("北京").Value())
address.Put("zip", gjson.NewJSONNumber(100000).Value())
obj.Put("address", address.GetData()) // 使用GetData()方法
obj.Put("address", address.GetData()) // 使用GetData()方法
// 创建数组
arr := gjson.NewJSONArray()
arr.Append(gjson.NewJSONString("item1").Value())
arr.Append(gjson.NewJSONNumber(123).Value())
obj.Put("items", arr.GetData()) // 使用GetData()方法
obj.Put("items", arr.GetData()) // 使用GetData()方法
// 序列化到JSON
jsonStr, _ := obj.ToJSON()
@ -34,6 +35,9 @@ func main() {
stringified, _ := gjson.Stringify(obj)
fmt.Printf("Stringify结果: %s\n", stringified)
// Parse
parsed, _ := gjson.Parse(jsonStr)
fmt.Printf("Parse结果: %v\n", parsed)
// 使用PrettyPrint格式化输出
pretty, _ := gjson.PrettyPrint(obj)
fmt.Printf("格式化输出:\n%s\n", pretty)
@ -86,7 +90,7 @@ func main() {
nestedObj := gjson.NewJSONObject()
nestedObj.Put("nestedProp", gjson.NewJSONString("nestedValue").Value())
jsonArray.Append(nestedObj.GetData()) // 使用GetData()方法
jsonArray.Append(nestedObj.GetData()) // 使用GetData()方法
arrayJson, _ := jsonArray.ToJSON()
fmt.Printf("JSON数组: %s\n", arrayJson)

81
parse.go Normal file
View File

@ -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}
}