登录
首页 >  Golang >  Go问答

将 json 转换为正确的结构,而不是使用接口

来源:stackoverflow

时间:2024-04-05 12:03:37 236浏览 收藏

大家好,我们又见面了啊~本文《将 json 转换为正确的结构,而不是使用接口》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

我正在努力创建一个数据结构来解组以下 json:

{
    "asks": [
        ["2.049720", "183.556", 1576323009],
        ["2.049750", "555.125", 1576323009],
        ["2.049760", "393.580", 1576323008],
        ["2.049980", "206.514", 1576322995]
    ],
    "bids": [
        ["2.043800", "20.691", 1576322350],
        ["2.039080", "755.396", 1576323007],
        ["2.036960", "214.621", 1576323006],
        ["2.036930", "700.792", 1576322987]
    ]
}

如果我将以下结构与接口一起使用,则没有问题:

type orderbook struct {
    asks [][]interface{} `json:"asks"`
    bids [][]interface{} `json:"bids"`
}

但我需要更严格的打字,所以我尝试过:

type bitfinexorderbook struct {
    pair string            `json:"pair"`
    asks [][]bitfinexorder `json:"asks"`
    bids [][]bitfinexorder `json:"bids"`
}

type bitfinexorder struct {
    price     string
    volume    string
    timestamp time.time
}

但不幸的是我没有成功。

这是我用来解析 kraken api 以检索订单簿的代码:

// loadkrakenorderbook is delegated to load the data related to pairs info
func loadkrakenorderbook(data []byte) (datastructure.bitfinexorderbook, error) {
    var err error

    // creating the maps for the json data
    m := map[string]interface{}{}
    var orderbook datastructure.bitfinexorderbook

    // parsing/unmarshalling json
    err = json.unmarshal(data, &m)

    if err != nil {
        zap.s().debugw("error unmarshalling data: " + err.error())
        return orderbook, err
    }

    a := reflect.valueof(m["result"])

    if a.kind() == reflect.map {
        key := a.mapkeys()[0]
        log.println("key: ", key)
        strct := a.mapindex(key)
        log.println("map: ", strct)
        m, _ := strct.interface().(map[string]interface{})
        log.println("m: ", m)
        data, err := json.marshal(m)
        if err != nil {
            zap.s().warnw("panic on key: ", key.string(), " err: "+err.error())
            return orderbook, err
        }
        log.println("data: ", string(data))
        err = json.unmarshal(data, &orderbook)
        if err != nil {
            zap.s().warnw("panic on key: ", key.string(), " during unmarshal. err: "+err.error())
            return orderbook, err
        }
        return orderbook, nil

    }
    return orderbook, errors.new("unable_parse_value")
}

我用于测试的数据如下:

{
    "error": [],
    "result": {
        "linkusd": {
            "asks": [
                ["2.049720", "183.556", 1576323009],
                ["2.049750", "555.125", 1576323009],
                ["2.049760", "393.580", 1576323008],
                ["2.049980", "206.514", 1576322995]
            ],
            "bids": [
                ["2.043800", "20.691", 1576322350],
                ["2.039080", "755.396", 1576323007],
                ["2.036960", "214.621", 1576323006],
                ["2.036930", "700.792", 1576322987]
            ]
        }
    }
}

编辑

注意:我在输入中收到的数据是我发布的最新 json,而不是 bidsasks 的数组。

我尝试集成@chmike 提出的解决方案。不幸的是,需要进行一些预处理,因为数据是我发布的最新 json。

因此,我已更改为以下代码,以便提取与 asksbids 相关的 json 数据。

func order(data []byte) (datastructure.BitfinexOrderBook, error) {
    var err error

    // Creating the maps for the JSON data
    m := map[string]interface{}{}
    var orderbook datastructure.BitfinexOrderBook
    // var asks datastructure.BitfinexOrder
    // var bids datastructure.BitfinexOrder
    // Parsing/Unmarshalling JSON
    err = json.Unmarshal(data, &m)

    if err != nil {
        zap.S().Warn("Error unmarshalling data: " + err.Error())
        return orderbook, err
    }

    // Extract the "result" json
    a := reflect.ValueOf(m["result"])

    if a.Kind() == reflect.Map {
        key := a.MapKeys()[0]
        log.Println("KEY: ", key)
        log.Println()
        strct := a.MapIndex(key)
        log.Println("MAP: ", strct)
        m, _ := strct.Interface().(map[string]interface{})
        log.Println("M: ", m)
        log.Println("Asks: ", m["asks"])
        log.Println("Bids: ", m["bids"])

        // Here i retrieve the asks array
        asks_data, err := json.Marshal(m["asks"])
        log.Println("OK: ", err)
        log.Println("ASKS: ", string(asks_data))
        var asks datastructure.BitfinexOrder
        // here i try to unmarshal the data into the struct
        asks, err = UnmarshalJSON(asks_data)
        log.Println(err)
        log.Println(asks)

    }
    return orderbook, errors.New("UNABLE_PARSE_VALUE")
}

不幸的是,我收到以下错误:

json:无法将数组解组为 json.number 类型的 go 值


解决方案


根据@flimzy的建议,您需要一个自定义的unmarshaler。这里是。

请注意,bitfinexorderbook 定义与您的定义略有不同。其中有一个错误。

// bitfinexorderbook is a book of orders.
type bitfinexorderbook struct {
    asks []bitfinexorder `json:"asks"`
    bids []bitfinexorder `json:"bids"`
}

// bitfinexorder is a bitfinex order.
type bitfinexorder struct {
    price     string
    volume    string
    timestamp time.time
}

// unmarshaljson decode a bifinexorder.
func (b *bitfinexorder) unmarshaljson(data []byte) error {
    var packeddata []json.number
    err := json.unmarshal(data, &packeddata)
    if err != nil {
        return err
    }
    b.price = packeddata[0].string()
    b.volume = packeddata[1].string()
    t, err := packeddata[2].int64()
    if err != nil {
        return err
    }
    b.timestamp = time.unix(t, 0)
    return nil
}

另请注意,此自定义解组器函数允许您将价格或数量转换为浮点数,这可能正是您想要的。

虽然您可以通过使用反射来破解,甚至可以编写你自己的解析器,最有效的方法是实现一个 json.unmarshaler

不过,还存在一些问题。

  1. 您要将 json 数组 转换为 struct,而不仅仅是其中的 interface{} 元素,因此它应该是:asks []bitfinexorderbids []bitfinexorder

  2. 您需要包装结构 bitfinexorderbook 才能使其使用其数据。它很简单,比使用反射简单得多。

  3. 默认情况下,json.unmarshaljson 数字 解组为 float64,这在解析 timestamp 时不是一件好事。您可以使用 json.newdecoder 获取解码器,然后使用 decoder.usenumber 强制使用字符串。

例如,

func (bo *bitfinexorder) unmarshaljson(data []byte) error {
    dec := json.newdecoder(bytes.newreader(data))
    dec.usenumber()

    var x []interface{}
    err := dec.decode(&x)
    if err != nil {
        return errparse(err.error())
    }

    if len(x) != 3 {
        return errparse("length is not 3")
    }

    price, ok := x[0].(string)
    if !ok {
        return errparse("price is not string")
    }

    volume, ok := x[1].(string)
    if !ok {
        return errparse("volume is not string")
    }

    number, ok := x[2].(json.number)
    if !ok {
        return errparse("timestamp is not number")
    }
    tint64, err := strconv.parseint(string(number), 10, 64)
    if err != nil {
        return errparse(fmt.sprintf("parsing timestamp: %s", err))
    }

    *bo = bitfinexorder{
        price:     price,
        volume:    volume,
        timestamp: time.unix(tint64, 0),
    }
    return nil
}

和主函数(包装结构):

func main() {
    x := struct {
        Result struct{ LINKUSD BitfinexOrderBook }
    }{}
    err := json.Unmarshal(data, &x)
    if err != nil {
        log.Fatalln(err)
    }

    bob := x.Result.LINKUSD
    fmt.Println(bob)
}

演示链接:https://play.golang.org/p/pC124F-3M_S .

注意:演示链接使用辅助函数来创建错误。有些人可能认为最好将辅助函数命名为 newerrinvalidbitfinexorder 或重命名错误。这不是这个问题的范围,我想为了打字方便,我现在将保留简称。

到这里,我们也就讲完了《将 json 转换为正确的结构,而不是使用接口》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>