登录
首页 >  Golang >  Go问答

解组在根级别没有键的元组

来源:stackoverflow

时间:2024-04-17 12:12:32 208浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《解组在根级别没有键的元组》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

我正在尝试使用 golang,并发现从 rest api 解析一些 json 是一个很好的用例。它看起来就像定义一个结构并将 api 响应解组到其中一样简单。

当然,我正在使用的 api 响应并不是一个很好的选择。我正在玩 craigslist jsonsearch - 响应是 2 个对象的数组。第一个对象是结果数组,第二个对象是杂项。元数据。

[  
   [  
      {  
         "ask":6000,
         "categoryid":145,
         "imagethumb":"https:\/\/images.craigslist.org\/01212_dz9pfxsmjeh_50x50c.jpg",
         "latitude":39.591784,
         "longitude":-105.083209,
         "posteddate":1533949799,
         "postingid":6642987803,
         "postingtitle":"1991 jeep wrangler yj 4.0 4x4 $6000 obo",
         "postingurl":"https:\/\/denver.craigslist.org\/cto\/d\/1991-jeep-wrangler-yj-40-4xobo\/6642987803.html"
      }
   ],
   {  
      "nongeocoded":2,
      "baseurl":"\/\/denver.craigslist.org",
      "clat":41.2077284889441,
      "clng":-101.993919320865,
      "clustered":0,
      "geocoded":118,
      "zoom":7
   }
]

事实上,这些对象都没有键,这就是我迷失的地方。

我创建了一个结构,我认为该结构应该映射到此响应。没有键作为字段标签,我迷失了...如果只有某种方式可以说响应中的第一个元素应该映射 results[] 结构,第二个项目应该映射到元数据结构。

type SearchResponse struct {
    Results []struct {
        Ask int
        CategoryID int
        ImageThumb string
        Latitude float32
        Longitude float32
        PostedDate int64
        PostingID int64
        PostingTitle string
        PostingURL string
    }`json:"??first element??"`
    Metadata struct{
        NonGeocoded int
        baseurl string
        clat float32
        clng float32
        clustered int
        geocoded int
        zoom int
    }`json:"??second element??"`
}


func main() {

    searchUrl := "https://denver.craigslist.org/jsonsearch/cta?query=jeep+wrangler&sort=rel&max_price=15000&auto_transmission=1"
    resp, _ := http.Get(searchUrl)
    bytes, _ := ioutil.ReadAll(resp.Body)

    var searchResp SearchResponse
    if err := json.Unmarshal(bytes, &searchResp); err != nil {
        panic(err)
    }

    fmt.Print("it worked!")
    resp.Body.Close()

}

有没有更简单/更好的方法来做到这一点?


解决方案


用这个https://github.com/Anderson-Lu/gofasion就可以了,很简单。

Gofasion是一个轻量级解析库,方便开发过程中接口JSON数据的解析。它最大的特点是支持链式调用,这意味着可以直接获取目标键名和键值,而无需预先定义数据的结构。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《解组在根级别没有键的元组》文章吧,也可关注golang学习网公众号了解相关技术文章。

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