登录
首页 >  Golang >  Go问答

解析非标准json的数据流 – GO

来源:stackoverflow

时间:2024-02-29 10:45:26 312浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《解析非标准json的数据流 – GO》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我正在编写一个简单的应用程序,该应用程序向返回该类型的异构 json 的 api 发出请求

{
  "results": [
    [123, "zho's mask", 10586],
    [345, "ravaging superior studded coat", 58]
  ]
}

最终,我希望能够使用结果响应中的特定索引。例如,我希望能够获得“zho's mask”,或者价格:10586。这是我正在使用 gw2tp 的 api。

go json 博客中的大多数示例都引用了不包含嵌套数组的更简单或直接的 json。

根据我读到的内容,因为我知道 json 响应的一般外观,所以我可以创建一个 go 结构并将其解组到该结构的实例中。但是,我无法为这项工作创建正确的结构。

这是我当前尝试创建适当的结构

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

// {"results":[[123,"zho's mask",3532]]}

type equipment struct {
    results []resarray
}

type resarray struct {
    medium []lastarray
}

type lastarray struct {
    info string
}

func main() {
    res, err := http.get("http://api.gw2tp.com/1/items?ids=123&fields=name,sell")
    if err != nil {
        log.fatal(err)
    }

    var equipment equipment

    data, err := ioutil.readall(res.body)
    if err != nil {
        fmt.print("readall error: ", err, "\n")
    }
    err = json.unmarshal(data, &equipment)
    if err != nil {
        fmt.print("unmarshal error: ", err, "\n")
    }

}

这是解组错误:

Unmarshal error: json: cannot unmarshal array into Go struct field Equipment.Results of type main.ResArray

最后,这是我目前对这个所需 go 结构的方法的灵感 golang 中的 json 简介。


解决方案


类型 resarray 结构体 {

但它不是一个结构体,而是一个切片!

type lastarray struct {
    info string
}

但它不是一个字符串,它有时是一个字符串,有时是一个数字。

执行此操作的简单方法是将您的类型定义为

type equipment struct {
    results [][]interface{}
}

它表示 results 包含一片......某物的切片。您可以命名中间类型,但这不是必需的。然后例如e.results[0][1].(string) 将是 "zho 的面具"

更好的方法是通过提供自定义 unmarshaljson 来实现 Unmarshaler 接口,如下所示:

type Equipment struct {
    Results []Item
}

type Item struct {
    ID int
    Name string
    Sell int
}

func (i *Item) UnmarshalJSON(b []byte) error {
    // We're deserializing into a struct, but in JSON it's a mixed-type array.
    var arr []interface{}
    err := json.Unmarshal(b, &arr)
    if err != nil {
        return fmt.Errorf("unmarshal Item underlying array: %w", err)
    }
    if len(arr) != 3 {
        return fmt.Errorf("Item underlying array should be 3 elements, got %d", len(arr))
    }

    // JSON numbers will become float64 when loaded into interface{} but we want int
    id, ok := arr[0].(float64)
    if !ok {
        return fmt.Errorf("expected float64 for Item.ID, got %T", arr[0])
    }
    i.ID = int(id)

    i.Name, ok = arr[1].(string)
    if !ok {
        return fmt.Errorf("expected string for Item.Name, got %T", arr[1])

    }

    sell, ok := arr[2].(float64)
    if !ok {
        return fmt.Errorf("expected float64 for Item.Sell, got %T", arr[2])
    }
    i.Sell = int(sell)
    return nil
}

请记住,这些类型与您向 api 请求的字段的确切列表结合在一起 - 如果您更改它,则必须更改类型加载它的解组函数来自数组。

今天关于《解析非标准json的数据流 – GO》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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