From 43aabcf6108a554ea568398a8f92002ad584539d Mon Sep 17 00:00:00 2001 From: kingecg Date: Sun, 8 Mar 2026 16:31:16 +0800 Subject: [PATCH] =?UTF-8?q?```=20feat(gjson):=20=E6=B7=BB=E5=8A=A0JSON?= =?UTF-8?q?=E5=80=BC=E6=AF=94=E8=BE=83=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增Compare函数用于比较两个JSONValue类型的值,支持字符串和数字类型比较。 函数会检查类型一致性并返回比较结果,相同类型返回0,小于返回-1,大于返回1。 ``` --- compare.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 compare.go diff --git a/compare.go b/compare.go new file mode 100644 index 0000000..7948750 --- /dev/null +++ b/compare.go @@ -0,0 +1,37 @@ +package gjson + +import ( + "errors" + "fmt" + "reflect" + "strings" +) + +func Compare(a, b JSONValue) (int, error) { + if a == nil || b == nil { + return 0, errors.New("cannot compare nil values") + } + + typeA := reflect.TypeOf(a) + typeB := reflect.TypeOf(b) + + if typeA != typeB { + return 0, fmt.Errorf("cannot compare different types: %s vs %s", typeA, typeB) + } + + switch vA := a.(type) { + case *JSONString: + vB := b.(*JSONString) + return strings.Compare(vA.value, vB.value), nil + case *JSONNumber: + vB := b.(*JSONNumber) + if vA.value < vB.value { + return -1, nil + } else if vA.value > vB.value { + return 1, nil + } + return 0, nil // 当两个数相等时返回0 + } + + return 0, nil // 默认返回,理论上不会执行到这里 +} \ No newline at end of file