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

将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

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

报告相同问题?