在 golang 中解组 JSON

我在让我的程序运行时遇到了很多麻烦。我想解组一些非常简单的东西,但不幸的是,它给了我很多问题。


这是我要解组的响应:


{"error":[],"result":{"XXBTZUSD":[[1647365820,"39192.0","39192.0","39191.9","39191.9","39191.9","0.18008008",10],[1647365880,"39186.1","39186.1","39172.0","39176.0","39174.4","0.13120077",10]],"last":1647408900}}


我写了这些结构来帮助解组


type Resp struct {

    Error   []string        `json:"error"`

    Result  Trades          `json:"result"`

}


type Trades struct {

    Pair    []OHLC          `json:"XXBTZUSD"`

    Last    float64         `json:"last"`

}


type OHLC struct {

    Time    float64

    Open    string

    High    string

    Low     string

    Close   string

    Vwa     string

    Volume  string

    Count   float64

}

我有一个函数调用,它发出 http 请求,然后解组数据。无论出于何种原因,当 Pair 类型为 []OHLC 或 []*OHLC 时,我的代码甚至会在启动 http 请求函数调用和后续解组之前结束。如果我将 Pair 类型更改为 interface{},它就会运行。不过,我想让它与 OHLC 结构一起使用。


开心每一天1111
浏览 112回答 2
2回答

鸿蒙传说

“对可能发生的事情有什么想法吗?”"XXBTZUSD"JSON数组中的元素本身就是数组,即"XXBTZUSD"是数组的数组。该OHLC类型是结构类型。stdlib 本身不会将 JSON 数组解组为 Go 结构。Go 结构可用于解组 JSON 对象。JSON 数组可以解组为 Go 切片或数组。如果您只是打印来自 json.Unmarshal 的错误,您会清楚地看到这就是问题所在:json:无法将数组解组到main.OHLC 类型的 Go 结构字段 Trades.result.XXBTZUSDhttps://go.dev/play/p/D4tjXZVzDI_w如果要将 JSON 数组解组为 Go 结构,则必须让 Go 结构类型实现json.Unmarshaler接口。func (o *OHLC) UnmarshalJSON(data []byte) error {    // first unmarshal the array into a slice of raw json    raw := []json.RawMessage{}    if err := json.Unmarshal(data, &raw); err != nil {        return err    }    // create a function that unmarshals each raw json element into a field    unmarshalFields := func(raw []json.RawMessage, fields ...interface{}) error {        if len(raw) != len(fields) {            return errors.New("bad number of elements in json array")        }        for i := range raw {            if err := json.Unmarshal([]byte(raw[i]), fields[i]); err != nil {                return err            }        }        return nil    }    // call the function    return unmarshalFields(        raw,        &o.Time,        &o.Open,        &o.High,        &o.Low,        &o.Close,        &o.Vwa,        &o.Volume,        &o.Count,    )}https://go.dev/play/p/fkFKLkaNaSU

ITMISS

您的代码有一些问题:从行尾删除分号,这是多余的。fmt.Errorf返回错误,而不是打印它,每次检查你的错误并传播它。我们可以在 golang 中将数字数组和字符串转换为结构。为了实现您想要的输出,我们需要先转换为中间容器,然后再转换为我们想要的输出:package mainimport (&nbsp; &nbsp; "errors"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "log"&nbsp; &nbsp; "net/http"&nbsp; &nbsp; //"strings"&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "io/ioutil")type Resp struct {&nbsp; &nbsp; Error&nbsp; []string `json:"error"`&nbsp; &nbsp; Result Trades&nbsp; &nbsp;`json:"result"`}type IntermediateResp struct {&nbsp; &nbsp; Error&nbsp; []string&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;`json:"error"`&nbsp; &nbsp; Result IntermediateTrades `json:"result"`}type IntermediateTrades struct {&nbsp; &nbsp; Pair [][]interface{} `json:"XXBTZUSD"`&nbsp; &nbsp; Last int&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;`json:"last"`}type Trades struct {&nbsp; &nbsp; Pair []OHLC `json:"result"`&nbsp; &nbsp; Last int&nbsp; &nbsp; `json:"last"`}type OHLC struct {&nbsp; &nbsp; TT&nbsp; &nbsp; &nbsp;float64&nbsp; &nbsp; Open&nbsp; &nbsp;string&nbsp; &nbsp; High&nbsp; &nbsp;string&nbsp; &nbsp; Low&nbsp; &nbsp; string&nbsp; &nbsp; Close&nbsp; string&nbsp; &nbsp; Vwap&nbsp; &nbsp;string&nbsp; &nbsp; Volume string&nbsp; &nbsp; Count&nbsp; float64}/*func main() {&nbsp; &nbsp; var data = [...]Trade{&nbsp; &nbsp; &nbsp; &nbsp; Trade{5, "op", "hi", "lo", "cl", "vw", "vo", 2},&nbsp; &nbsp; &nbsp; &nbsp; Trade{5, "op", "hi", "lo", "cl", "vw", "vo", 2},&nbsp; &nbsp; }}*/func main() {&nbsp; &nbsp; fmt.Println("in main")&nbsp; &nbsp; err := getOhlc()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }}func buildOHLC(l []interface{}) (*OHLC, error) {&nbsp; &nbsp; if len(l) < 8 {&nbsp; &nbsp; &nbsp; &nbsp; return nil, errors.New("short list")&nbsp; &nbsp; }&nbsp; &nbsp; return &OHLC{&nbsp; &nbsp; &nbsp; &nbsp; TT:&nbsp; &nbsp; &nbsp;l[0].(float64),&nbsp; &nbsp; &nbsp; &nbsp; Open:&nbsp; &nbsp;l[1].(string),&nbsp; &nbsp; &nbsp; &nbsp; High:&nbsp; &nbsp;l[2].(string),&nbsp; &nbsp; &nbsp; &nbsp; Low:&nbsp; &nbsp; l[3].(string),&nbsp; &nbsp; &nbsp; &nbsp; Close:&nbsp; l[4].(string),&nbsp; &nbsp; &nbsp; &nbsp; Vwap:&nbsp; &nbsp;l[5].(string),&nbsp; &nbsp; &nbsp; &nbsp; Volume: l[6].(string),&nbsp; &nbsp; &nbsp; &nbsp; Count:&nbsp; l[7].(float64),&nbsp; &nbsp; }, nil}func convert(r IntermediateResp) (*Resp, error) {&nbsp; &nbsp; result := &Resp{Error: r.Error, Result: Trades{Pair: make([]OHLC, len(r.Result.Pair)), Last: r.Result.Last}}&nbsp; &nbsp; for i, v := range r.Result.Pair {&nbsp; &nbsp; &nbsp; &nbsp; ohlc, err := buildOHLC(v)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return nil, err&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; result.Result.Pair[i] = *ohlc&nbsp; &nbsp; }&nbsp; &nbsp; return result, nil}func getOhlc() error {&nbsp; &nbsp; fmt.Println("in ohlc func")&nbsp; &nbsp; resp, err := http.Get("https://api.kraken.com/0/public/OHLC?pair=XXBTZUSD")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return fmt.Errorf("error after request, %v", err)&nbsp; &nbsp; }&nbsp; &nbsp; defer resp.Body.Close()&nbsp; &nbsp; body, err := ioutil.ReadAll(resp.Body)&nbsp; &nbsp; fmt.Println(string(body))&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return fmt.Errorf("error when reading %v", err)&nbsp; &nbsp; }&nbsp; &nbsp; var jsonData IntermediateResp&nbsp; &nbsp; err = json.Unmarshal(body, &jsonData)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return fmt.Errorf("error when unmarshalling %v", err)&nbsp; &nbsp; }&nbsp; &nbsp; if len(jsonData.Error) > 0 {&nbsp; &nbsp; &nbsp; &nbsp; return fmt.Errorf("error")&nbsp; &nbsp; }&nbsp; &nbsp; convertedOhlc, err := convert(jsonData)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return fmt.Errorf("error when convertedOhlc %v", err)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(convertedOhlc)&nbsp; &nbsp; return nil}我们定义 IntermediateResp 和 IntermediateTrades 用于 Unmarshaling json,然后将其转换为实际的 Resp。Trades我认为另一种方法是对结构使用自定义 Unmarshal 。
打开App,查看更多内容
随时随地看视频慕课网APP