dttphb59319 2016-08-09 22:15
浏览 441
已采纳

如何在Golang中将具有两种不同数据类型的JSON数组解析为结构

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.

</div>
  • 写回答

1条回答 默认 最新

  • duanjieyi6582 2016-08-10 04:37
    关注

    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
    ", orders.A[0][0].(string))     
        fmt.Printf("%f
    ", 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 分析下图所示同步时序逻辑电路的逻辑功能。
  • ¥15 halcon联合c#遇到了问题不能解决
  • ¥15 xshell无法连接提示ssh服务器拒绝密码
  • ¥15 AT89C52单片机C语言关于串口通信的位操作
  • ¥20 需要步骤截图(标签-服务器|关键词-map)
  • ¥50 gki vendor hook
  • ¥15 灰狼算法和蚁群算法如何结合
  • ¥15 这是一个利用ESP32自带按键和LED控制的录像代码,编译过程出现问题,请解决并且指出错误,指导如何处理 ,协助完成代码并上传代码
  • ¥20 stm32f103,hal库 hal_usart_receive函数接收不到数据。
  • ¥20 求结果和代码,sas利用OPTEX程序和D-efficiency生成正交集