0

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])
        }
    }
3
  • 2
    Edit to make a minimal example. More specifically, replace the code to fetch the JSON text with a literal string containing the JSON text. Commented May 4, 2018 at 16:25
  • Possible duplicate of Serialize a mixed type JSON array in Go Commented May 4, 2018 at 16:33
  • I updated the code @ThunderCat to make a minimal example Commented May 4, 2018 at 16:34

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.