douxi3404 2018-08-11 14:15
浏览 11

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

I'm trying to cut my teeth with golang, and figured parsing some json from a rest api is a good use case. It looked to be as simple as defining a struct and unmarshaling the api response into that.

Naturally the api response I am playing with is not exactly a great candidate for this. I am playing with craigslist jsonsearch - and the response is an array of 2 objects. The first object is an array of results, the second object is misc. metadata.

[  
   [  
      {  
         "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
   }
]

The fact that neither of these objects have keys is where I am getting lost.

I have created a struct that I believe should map to this response. Without keys to as field tags, I am lost... If there was only some way to say the first element in the response should map the the Results[] struct and the second item to the Metadata struct.

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()

}

Is there a easier/better way to do this?

  • 写回答

1条回答 默认 最新

  • dtwxt88240 2018-08-24 01:50
    关注

    Just use this one https://github.com/Anderson-Lu/gofasion. It's easy.

    Gofasion is a lightweight parsing library that facilitates the parsing of interface JSON data during development. Its biggest feature is to support chained calls, which means that the target key name and key value can be directly obtained without pre-defining the structure of the data.

    评论

报告相同问题?