How to parse JSON arrays with two different data types into a struct in Golang

做~自己de王妃 提交于 2021-01-27 22:13:33

问题


I have JSON that looks like this:

{
    "a": [
          [
              "12.58861425",
              10.52046452
          ],
          [
              "12.58861426",
              4.1073
          ]
        ]
    "b": [
          [
              "12.58861425",
              10.52046452
          ],
          [
              "12.58861426",
              4.1073
          ]
        ]
    "c": "true"
    "d": 1234
}
        

I want to unmarshall this into a struct I created:

type OrderBook struct {
	A [][2]float32 `json:"a"`
	B [][2]float32 `json:"b"`
        C string `json:"c"`
	D uint32 `json:"d"`
}

//Note this won't work because the JSON array contains a string and a float value pair rather than only floats.

Normally I would then convert this JSON into a struct in Golang as so:

orders := new(OrderBook)
err = json.Unmarshal(JSON, &orders)

Since I can't define the type struct to match the JSON this won't work. Doing a bit of reading, I think Unmarshal-ing into an interface, and then using the interface data through type checking may be a solution.

Am I going in the right direction with this?
A template showing how I might go about using the data once it's in the interface would really help.


回答1:


Why not just leave out declaring the types of the A and B slices like so?

data := []byte(`{"a": [["12.58861425",10.52046452],["12.58861426",4.1073]],"b": [["12.58861425",10.52046452],["12.58861426",4.1073]],"c": "true","d": 1234}`)

type OrderBook struct {
    A [][2]interface{} `json:"a"`
    B [][2]interface{} `json:"b"`
    C string           `json:"c"`
    D uint32           `json:"d"`
}
orders := new(OrderBook)
err := json.Unmarshal(data, &orders)
if err != nil {
    fmt.Printf(err.Error())
} else {
    fmt.Printf("%s\n", orders.A[0][0].(string))     
    fmt.Printf("%f\n", orders.A[0][1].(float64))
}

There's an example in the playground: https://play.golang.org/p/0MUY-yOYII

I must disagree with evanmcdonnal, there are certainly use cases where where rolling your own Unmarshaller makes sense, this I do not believe is one of them. It doesn't get much simpler than what is shown here.



来源:https://stackoverflow.com/questions/38861295/how-to-parse-json-arrays-with-two-different-data-types-into-a-struct-in-golang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!