read online JSON and save values to CSV in Golang -


i'm able decode in-programme json.

however, want decode online json , save values values in csv file.

here current code: http://play.golang.org/p/tvz4ceal-r

package main  import "fmt" import "encoding/json"   type response struct {     region string `json:"1"`     trends []string `json:"2"` }    func main() {      str := `{"1": ["apple", "banana"], "2": ["apple", "peach"]}`     res := &response{}     json.unmarshal([]byte(str), &res)     fmt.println(res.trends) } 

the json i'm trying process instead of current-value of str here: http://hawttrends.appspot.com/api/terms/

res.trends values want , want take each of them , write them .csv

that json malformed, should return array not object, can use map achieve want : play

func main() {      str := `{"1": ["apple", "banana"], "2": ["apple", "peach"]}`     res := map[string][]string{}     json.unmarshal([]byte(str), &res)     fmt.println(res) } 

update play :

func get_json(url string) []byte {     resp, err := http.get(url)     if err != nil {         panic(err)     }     defer resp.body.close()     body, err := ioutil.readall(resp.body)     if err != nil {         panic(err)     }     return body }  func main() {      res := map[string][]string{}     json.unmarshal(get_json("http://hawttrends.appspot.com/api/terms/"), &res)     k, v := range res {         fmt.printf("%s=%#v\n", k, v)     } } 

i recommend go through documentation, it's straight forward.

check :

  1. http://tour.golang.org/#1
  2. http://golang.org/pkg/net/http/

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -