douren8379
2016-11-16 01:09
浏览 177
已采纳

如何在Golang中正确解组无键JSON数组?

I have JSON data which looks like this:

[
  {
    "globalTradeID": 64201000,
    "tradeID": 549285,
    "date": "2016-11-11 23:51:58",
    "type": "buy",
    "rate": "10.33999779",
    "amount": "0.02176472",
    "total": "0.22504715"
  },
  {
    "globalTradeID": 64200631,
    "tradeID": 549284,
    "date": "2016-11-11 23:48:39",
    "type": "buy",
    "rate": "10.33999822",
    "amount": "0.18211700",
    "total": "1.88308945"
  }...
]

I've tried to unmarshall this JSON by defining a type:

type TradeHistoryResponse   []TradeHistoryInfo

type TradeHistoryInfo struct {
    GlobalTradeID   int64   `json:"globalTradeID"`
    TradeID         int64   `json:"tradeID"`
    Date            string  `json:"date"`
    Type            string  `json:"type"`
    Rate            float64 `json:"rate,string"`
    Amount          float64 `json:"amount,string"`
    Total           float64 `json:"total,string"`
}

And then pulling the JSON data as so:

    //Read response
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return nil, fmt.Errorf("[Poloniex] (doRequest) Failed to parse response for query to %s! (%s)", reqURL, err.Error())
    } 

    //Convert JSON to struct

    var THR TradeHistoryResponse
    err = json.Unmarshal(body, &THR)
    if err != nil {
        return nil, fmt.Errorf("[Poloniex] (doRequest) Failed to convert response into JSON for query to %s! (%s)", reqURL, err.Error())
    }

I get the following error:

(json: cannot unmarshal object into Go value of type poloniex.TradeHistoryResponse)

My best guess why the Unmarshall doesn't work is because the array is key-less?

Would love to have some clarification on the matter on how I might best get this working.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • donglei7152 2016-11-16 06:16
    已采纳

    I didn't think unmarhsalling an array in a JSON like you intended actually works but to the props of encoding/json it does. Example code: package main

    import (
        "encoding/json"
        "fmt"
        "log"
    )
    
    var mjs string = "[" +
        "{" +
        `"globalTradeID": 64201000,
                              "tradeID": 549285,
                              "date": "2016-11-11 23:51:58",
                              "type": "buy",
                              "rate": "10.33999779",
                              "amount": "0.02176472",
                              "total": "0.22504715"
                            },
                            {
                              "globalTradeID": 64200631,
                              "tradeID": 549284,
                              "date": "2016-11-11 23:48:39",
                              "type": "buy",
                              "rate": "10.33999822",
                              "amount": "0.18211700",
                              "total": "1.88308945"
                            }
                            ]`
    
    type TradeHistoryResponse []TradeHistoryInfo
    
    type TradeHistoryInfo struct {
        GlobalTradeID int64   `json:"globalTradeID"`
        TradeID       int64   `json:"tradeID"`
        Date          string  `json:"date"`
        Type          string  `json:"type"`
        Rate          float64 `json:"rate,string"`
        Amount        float64 `json:"amount,string"`
        Total         float64 `json:"total,string"`
    }
    
    func main() {
    
        //Convert JSON to struct
    
        var THR TradeHistoryResponse
        err := json.Unmarshal([]byte(mjs), &THR)
        if err != nil {
        log.Fatal(err)
        }
      for _, v := range THR {
        fmt.Printf("%+v", v)
        fmt.Printf("
    ")
      }
    }
    

    This prints out all the values as expected. So it doesn't have a problem converting the json values to float/int either (which would have been my second guess).

    Are you sure you aren't modifying the Body in any way ? And that the example you give cover all edge cases ?

    Could you add:

    fmt.Println(string(body)) 
    

    to the second error block and log the error it give here.

    Also what version of go are you using ? I wouldn't exclude the possibility of encoding/json to have changed between versions. In the end, if this is indeed the case the easy fix would be taking your response as a string, removing all whitespaces and splitting at "}'{" as in:

    fmtBody := strings.Replace(string(body), "
    ", "", -1)
    fmtBody = strings.Replace(string(fmtBody), "\w", "", -1)
    fmtBody = strings.Replace(string(fmtBody), "[", "", -1)
    fmtBody = strings.Replace(string(fmtBody), "]", "", -1)
    var goArrOfYourJsonsObj []String = strings.Split(fmtBody, "},{")
    for k, _ := range goArrOfYourJsonsObj {
      goArrOfYourJsonsObj[k] += "}"
    }
    

    And now you have your JSON objects neatly separated into a go array of types String which, can be used in Unmarshall as []byte(val).

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douju1953 2016-11-16 01:31

    TradeHistoryResponse is a type no a variable, you have to create a var of type TradeHistoryResponse, like this:

    var th TradeHistoryResponse
    
    //Convert JSON to struct
    err = json.Unmarshal(body, &th)
    // ...
    
    fmt.Printf("%+v
    ", th)
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题