json - 为什么golang json number不能像“10”那样转换int或string int?
问题描述
我想将接口值转换为数字,但是当接口是数字或数字字符串时,它不起作用,我不知道为什么我们不能这样转换?
package main
import (
"encoding/json"
"fmt"
"reflect"
)
func main() {
number := 10
strNumber := "10"
test(number)
test(strNumber)
}
func test(i interface{}) {
strNum, ok := i.(json.Number)
fmt.Println(strNum, ok, reflect.TypeOf(i))
}
它将产生如下结果:
false int
false string
解决方案
这是您在 Go 中的示例:
package main
import (
"encoding/json"
"fmt"
"strconv"
)
func main() {
number := 10
strNumber := "10"
test(number)
test(strNumber)
}
func test(i interface{}) {
var strNum string
switch x := i.(type) {
case int:
strNum = strconv.Itoa(x)
case string:
if _, err := strconv.ParseInt(x, 10, 64); err == nil {
strNum = x
}
}
jsonNum := json.Number(strNum)
fmt.Printf("%[1]v %[1]T\n", jsonNum)
}
游乐场: https: //play.golang.org/p/iDSxrORX9yc
输出:
10 json.Number
10 json.Number
推荐阅读
- javascript - 套接字发射只接收数组中的第一个对象
- javascript - 拖动时激活断点
- postgresql - 在没有 DO UPDATE 的情况下获取 ON CONFLICT 列
- python - 使用python将Dataframe转换为字典
- sql - 通过 JDBC 在 ORACLE XE 18 中创建非 ORACLE_MAINTAINED 用户
- angular - Angular:将 base-href 与 scss url 结合使用
- ssis - SSIS 完整结果集不包含任何记录 - 用于 Foreach 循环
- javascript - ExtJS - 我应该把新的代理文件放在哪里?
- python - 如何在 djnago 中总结外键模型的数字
- python - 蟒蛇 -m 点子
错误:未知命令