/* Here is an example of the JSON I'm trying to parse [It's from the Guardian website]:{"response":{"status":"ok","userTier":"developer","total":19,"startIndex":1,"pageSize":1,"currentPage":1,"pages":19,"orderBy":"relevance","results":[{"type":"article","sectionId":"technology","webTitle":"Apple removes adblockers that work on Facebook and other third-party apps","webPublicationDate":"2015-10-09T10:02:09Z","id":"technology/2015/oct/09/apple-removes-iphone-adblockers-facebook-third-party-apps","webUrl":"http://www.theguardian.com/technology/2015/oct/09/apple-removes-iphone-adblockers-facebook-third-party-apps","apiUrl":"http://content.guardianapis.com/technology/2015/oct/09/apple-removes-iphone-adblockers-facebook-third-party-apps","sectionName":"Technology"}]}}I want to get "webTitle" which is nested inside "results" which is nested inside "response"*/// get the JSON from URLresponse,err:=//http.Get("http://content.guardianapis.com/search?from-date=2015-10-03&q=iphone&api-key=zksex4jr82dg2gkcqtyq5xp8")iferr!=nil{fmt.Printf("%s",err)os.Exit(1)}else{deferresponse.Body.Close()contents,err:=ioutil.ReadAll(response.Body)iferr!=nil{fmt.Printf("%s",err)os.Exit(1)}//unmarshal JSON into "parse1"varparse1map[string]interface{}iferr:=json.Unmarshal(contents,&parse1);err!=nil{panic(err)}parse2:=parse1["response"].(map[string]interface{})["results"].([]interface{})/* I can't pretend to properly understand what's going on here, but this works to extract the nested 'webTitle' into a string *///range across slice of maps looking for field called 'webTitle' ???for_,headline:=rangeparse2{ifheadline,ok:=headline.(map[string]interface{});ok{//convert it to a stringheadlinetext:=headline["webTitle"].(string)}}
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.