go - 将 influxdb 结果读入字符串导致错误 : interface{} is json. Number, not string

标签 go influxdb

我正在尝试将 influxdb record(类型:[]interface{})转换为 []string,以便我可以编写它到 csv。

记录

[2018-12-20T07:26:23Z 90 123.2132 12.3232 30 1 user]

代码

s := make([]string, len(record))
for i, v := range record {
    s[i] = v.(string)
}

但是我得到了这个错误

interface {} is json.Number, not string

刚接触golang,对interface和json不太熟悉

最佳答案

我相信你的记录数组是由你的数据库驱动程序生成的,有点像这样:

record := make([]interface{}, 0, 10)
dec := json.NewDecoder(strings.NewReader(`["2018-12-20T07:26:23Z", 90, 123.2132, 12.3232, 30, 1, "user"]`))
dec.UseNumber()
dec.Decode(&record)

所有数字都生成为 json.Number 而不是 float64。由于 json.Number 支持到字符串的简单转换,您可以将该接口(interface)与简单的 type switch 一起使用。这样做:

s := make([]string, len(record))
for i, v := range record {
    switch val := v.(type) {
    case string:
        s[i] = val
    case json.Number:
        s[i] = val.String()
    default:
        panic(fmt.Sprintf("unhandled type: %T", v))
    }
}

实际操作如下: https://play.golang.org/p/jD_z94vQ7Wt

关于go - 将 influxdb 结果读入字符串导致错误 : interface{} is json. Number, not string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53879152/

相关文章:

docker - Docker容器间通讯

javascript - 在Karate框架中的RunnerTest.have中编写javascript公共(public)函数

python - 在 python 中使用 Influxdb 客户端 - 错误 : 'InfluxDBClient' object has no attribute 'create_database' /' get_list_database '

java - 如何以编程方式从 InfluxDb 中删除测量值?

go - 如何暂停和恢复goroutine?

go - 在 Go 中构建使用 "oneof"的 protobuf 消息

mysql - Beego QueryRows 映射失败

go - 尝试包装函数时函数用作值错误

postgresql - 如何在 Go 中表示 PostgreSQL 区间

ubuntu - 如何在 Alpine 上安装 Debian 软件包?