Golang用一个字符串和一个float64将JSON解码为切片 [英] Golang decoding JSON into slice with one string and one float64

查看:47
本文介绍了Golang用一个字符串和一个float64将JSON解码为切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对服务器上的数据库运行查询.问题是,当我尝试将JSON解码为2D切片时,出现错误,因为其中一个元素是字符串,另一个元素是float64.

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.

我尝试解决此问题的一种方法是在解码JSON字符串之前,先加引号使数字成为字符串,然后再对其进行解码.但是有更好的方法吗?有什么办法可以在可以解码JSON代码的地方修改代码的结构?

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:无法将数字编组为字符串类型的Go结构字段.values

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

推荐答案

这是一个非常不幸的API,必须使用,但是有一种(有些笨拙的)解决方法:

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)

可运行的示例: https://play.golang.org/p/ikIHnXlSlYx

这篇关于Golang用一个字符串和一个float64将JSON解码为切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆