在Go语言中打印JSON文件中的值。

huangapple go评论165阅读模式
英文:

Print value from JSON file in Go

问题

我正在使用Go语言制作一个货币转换器,它会下载一个JSON文件,然后读取它以打印当前的货币汇率。我不明白如何打印值,我知道我需要使用Unmarshal,但我不明白如何使用它。

例如,我想从JSON文件中打印值1.4075

这是JSON文件(从这里获取):

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

以下是我目前完成的部分。

  1. package main
  2. import(
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. )
  7. func main(){
  8. fromCurrency:="GBP"
  9. toCurrency:="USD"
  10. out, err := os.Create("latest.json")
  11. if err != nil{
  12. fmt.Println("Error:", err)
  13. }
  14. defer out.Close()
  15. resp, err := http.Get("http://api.fixer.io/latest?base=" + fromCurrency + "&symbols=" + toCurrency)
  16. defer resp.Body.Close()
  17. _, err = io.Copy(out, resp.Body)
  18. if err!= nil{
  19. fmt.Println("Error:", err)
  20. }
  21. }
英文:

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):

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

Here is what I have done so far.

  1. package main
  2. import(
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. )
  7. func main(){
  8. fromCurrency:="GBP"
  9. toCurrency:="USD"
  10. out, err := os.Create("latest.json")
  11. if err != nil{
  12. fmt.Println("Error:", err)
  13. }
  14. defer out.Close()
  15. resp, err := http.Get("http://api.fixer.io/latest?base=" + fromCurrency + "&symbols=" + toCurrency)
  16. defer resp.Body.Close()
  17. _, err = io.Copy(out, resp.Body)
  18. if err!= nil{
  19. fmt.Println("Error:", err)
  20. }
  21. }

答案1

得分: 2

将响应解码为与响应形状匹配的类型。例如:

  1. var data struct {
  2. Base string
  3. Date string
  4. Rates map[string]float64
  5. }
  6. if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
  7. log.Fatal(err)
  8. }

打印相应的值:

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

完整示例:点击这里

英文:

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

  1. var data struct {
  2. Base string
  3. Date string
  4. Rates map[string]float64
  5. }
  6. if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
  7. log.Fatal(err)
  8. }

Print the the appropriate value:

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

complete example

huangapple
  • 本文由 发表于 2016年4月10日 06:19:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/36523400.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定