```
feat(gjson): 添加JSON值比较功能 新增Compare函数用于比较两个JSONValue类型的值,支持字符串和数字类型比较。 函数会检查类型一致性并返回比较结果,相同类型返回0,小于返回-1,大于返回1。 ```
This commit is contained in:
parent
7b7115fecd
commit
43aabcf610
|
|
@ -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 // 默认返回,理论上不会执行到这里
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue