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?