如何通过JSON为Golang解组嵌套数组中的对值 [英] How to Unmarshal the pair values in an nested array by json for Golang

查看:59
本文介绍了如何通过JSON为Golang解组嵌套数组中的对值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JSON数据如下:

{"xxx_xxx":{"asks":[[0.00000315,1022.53968253],[0.00000328,200],[0.00000329,181.70008541]],"bids":[[0.00000254,2685.36319716],[0.00000253,600],[0.0000025,1000]]}}

结构为:

type Depth struct {
    XXX_XXX struct {
        Asks []struct {
            Num0 float64 `json:"0"`
            Num1 float64 `json:"1"`
        } `json:"asks"`
        Bids []struct {
            Num0 float64 `json:"0"`
            Num1 float64 `json:"1"`
        } `json:"bids"`
    } `json:"xxx_xxx"`
}

当尝试按以下方式在go-lang中进行映射时:

when try to map in go-lang as following:

json.Unmarshal(r, &depth)

将获得所有零数组,如下所示:

will get all zero arrays like following:

{{[{0 0} {0 0} {0 0} ] [{0 0} {0 0} {0 0} ]}}

它没有达到我预期的结果. 如何解决这个问题?

It does not come up the result as I expected. How to solve this problem?

HERE是操场上的代码: https://play.golang.org/p/wxFV6Mv26t

HERE is the code on playground: https://play.golang.org/p/wxFV6Mv26t

推荐答案

要约和出价是数组类型,而不是结构类型.

Asks and bids are array types not struct types.

这是一个有效的游乐场示例

是添加Nums类型的示例,该类型具有可以使用的OneTwo方法,因为这些似乎是您期望的格式.您可以在这些方法中添加一些错误检查,以确保格式也正确.

Below is an example that adds a Nums type that has a One and Two method you can use since those seem to be the format you are expecting. You could add some error checking in these methods to ensure the format is correct too.,

type Depth struct {
    XXX XXX `json:"xxx_xxx"`
}

type XXX struct {
    Asks []Nums `json:"asks"`
    Bids []Nums `json:"bids"`
}

type Nums []float64

func (n Nums) One() float64 {
    if len(n) > 0 {
         return n[0]
    }
    return 0
}

func (n Nums) Two() float64 {
    if len(n) > 1 {
        return n[1]
    }
    return 0
}

这篇关于如何通过JSON为Golang解组嵌套数组中的对值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆