1

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)
 }
}
asked Apr 9, 2016 at 22:19

1 Answer 1

2

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

answered Apr 9, 2016 at 23:09
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. This is right what I was looking for!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.