Lakhan Mankani
Lakhan Mankani

Reputation: 69

Print value from JSON file in Go

I am making a currency converter in Go which downloads a JSON file and it then reads it to print the current currency rate. I am unable to understand how to print the value, I know I have to use Unmarshal but I don't understand how to use it.

For example I want to print the value 1.4075 from the JSON file.

Here is the JSON file (This is pulled from here):

{"base":"GBP","date":"2016-04-08","rates":{"USD":1.4075}}

Here is what I have done so far.

package main

import(
  "encoding/json"
  "fmt"
  "io/ioutil"
)

func main(){
  fromCurrency:="GBP"
  toCurrency:="USD"

  out, err := os.Create("latest.json")
  if err != nil{
      fmt.Println("Error:", err)
  }
  defer out.Close()
  resp, err := http.Get("http://api.fixer.io/latest?base=" +    fromCurrency + "&symbols=" + toCurrency)
  defer resp.Body.Close()
  _, err = io.Copy(out, resp.Body)
  if err!= nil{
      fmt.Println("Error:", err)
  }
}

Upvotes: 1

Views: 85

Answers (1)

Thundercat
Thundercat

Reputation: 120951

Decode the response to a type that matches the shape of the response. For example:

var data struct {
    Base  string
    Date  string
    Rates map[string]float64
}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
    log.Fatal(err)
}

Print the the appropriate value:

if r, ok := data.Rates["USD"]; ok {
    log.Println("Rate", r)
} else {
    log.Println("no rate")
}

complete example

Upvotes: 2

Related Questions