go port
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
package tron
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// ValueString coerces a decoded JSON value to a string. It handles the
|
||||
// json.Number type produced when decoding with UseNumber so large integers are
|
||||
// preserved exactly.
|
||||
func ValueString(v any) string {
|
||||
switch x := v.(type) {
|
||||
case nil:
|
||||
return ""
|
||||
case string:
|
||||
return x
|
||||
case json.Number:
|
||||
return x.String()
|
||||
case float64:
|
||||
return strconv.FormatFloat(x, 'f', -1, 64)
|
||||
case bool:
|
||||
if x {
|
||||
return "true"
|
||||
}
|
||||
return "false"
|
||||
default:
|
||||
return fmt.Sprintf("%v", x)
|
||||
}
|
||||
}
|
||||
|
||||
// ValueInt64 coerces a decoded JSON value to an int64. Missing or non-numeric
|
||||
// values yield 0, matching Python's treatment of absent dict keys.
|
||||
func ValueInt64(v any) int64 {
|
||||
switch x := v.(type) {
|
||||
case json.Number:
|
||||
if i, err := x.Int64(); err == nil {
|
||||
return i
|
||||
}
|
||||
f, _ := x.Float64()
|
||||
return int64(f)
|
||||
case float64:
|
||||
return int64(x)
|
||||
case int64:
|
||||
return x
|
||||
case int:
|
||||
return int64(x)
|
||||
case string:
|
||||
i, _ := strconv.ParseInt(x, 10, 64)
|
||||
return i
|
||||
}
|
||||
return 0
|
||||
}
|
||||
Reference in New Issue
Block a user