duanguai2781 2018-12-21 04:27
浏览 374
已采纳

将influxdb结果读入字符串会导致错误:interface {}是json.Number,而不是字符串

I'm trying to convert an influxdb record (type: []interface{}) to []string so I can write it to csv.

Record

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

Code

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

But I got this error

interface {} is json.Number, not string

I'm new to golang and not too familiar with interface and json

  • 写回答

1条回答 默认 最新

  • douxi3432 2018-12-21 05:20
    关注

    I believe your record array is generated somewhat like this by your database driver:

    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)
    

    All numbers are generated as json.Number instead float64. Since json.Number support a simple conversion to string, you may use that interface along with a simple type switch to do this:

    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))
        }
    }
    

    See this in action: https://play.golang.org/p/jD_z94vQ7Wt

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Windows Script Host 无法找到脚本文件"C:\ProgramData\Player800\Cotrl.vbs”
  • ¥15 matlab自定义损失函数
  • ¥15 35114 SVAC视频验签的问题
  • ¥15 impedancepy
  • ¥15 求往届大挑得奖作品(ppt…)
  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图