douhui7136 2018-05-04 16:18
浏览 97

Golang用一个字符串和一个float64将JSON解码为切片

I am running a query on a database that I have on a sever. The problem is when I am trying to decode the JSON into a 2D slice I get an error because one of them elements is a string and the other element is a float64.

One way I tried to resolve this issue is my modifying the JSON string before I decode it by adding quotes to make the number a string. But is there a better way of doing this? Is there a way I can modify the struct of my code where I am able to decode the JSON code?

2018/05/04 12:32:19 json: cannot unmarshal number into Go struct field .values of type string

import (
"fmt"
"encoding/json"
"strings"
"io"
"log"
)

func main(){
    str := "{\"results\":[{\"statement_id\":0,\"series\":[{\"name\":\"_\",\"columns\":[\"time\",\"last\"],\"values\":[[\"2018-03-20T18:45:57.07Z\",142774272]]}]}]}"

    type Response struct {
        Results []struct {
            StatementID int `json:"statement_id"`
            Series []struct {
                Name string `json:"name"`
                Columns []string `json:"columns"`
                Values [][]string `json:"values"`
            } `json:"series"`
        } `json:"results"`
    }

    dec := json.NewDecoder(strings.NewReader(str))
        for {
            var m Response
            if err := dec.Decode(&m); err == io.EOF {
                break
            } else if err != nil {
                log.Fatal(err)
            }
            fmt.Println(m.Results[0].Series[0].Values[0])
        }
    }
  • 写回答

1条回答 默认 最新

  • dougou6727 2018-05-04 16:30
    关注

    This is a really unfortunate API to have to work with, but there is a (somewhat clumsy) workaround:

    Values [][]interface{} `json:"values"`
    

    Basically this is saying "an array of things of unknown type". This will allow the decoder to decode properly, but it will require you to do some type assertions to actually use the values, in order to get from "unknown type" to a known type that you can actually use:

    strVal := m.Results[0].Series[0].Values[0][0].(string)
    floatVal := m.Results[0].Series[0].Values[0][1].(float64)
    

    Runnable example: https://play.golang.org/p/ikIHnXlSlYx

    评论

报告相同问题?

悬赏问题

  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)