Snippets

stíobhart matulevicz KK8pb: Untitled snippet

Created by stíobhart matulevicz
/* 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 URL

response, err := //http.Get("http://content.guardianapis.com/search?from-date=2015-10-03&q=iphone&api-key=zksex4jr82dg2gkcqtyq5xp8")
		if err != nil {
			fmt.Printf("%s", err)
			os.Exit(1)
		} else {
			defer response.Body.Close()
			contents, err := ioutil.ReadAll(response.Body)
			if err != nil {
				fmt.Printf("%s", err)
				os.Exit(1)
			}

//unmarshal JSON into "parse1"
var parse1 map[string]interface{}
if err := 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 := range parse2 {
			if headline, ok := headline.(map[string]interface{}); ok {
				//convert it to a string
				headlinetext: = headline["webTitle"].(string)

			}
		}
        

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.