英文:
Print value from JSON file in Go
问题
我正在使用Go语言制作一个货币转换器,它会下载一个JSON文件,然后读取它以打印当前的货币汇率。我不明白如何打印值,我知道我需要使用Unmarshal,但我不明白如何使用它。
例如,我想从JSON文件中打印值1.4075
。
这是JSON文件(从这里获取):
{"base":"GBP","date":"2016-04-08","rates":{"USD":1.4075}}
以下是我目前完成的部分。
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)
}
}
英文:
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)
}
}
答案1
得分: 2
将响应解码为与响应形状匹配的类型。例如:
var data struct {
Base string
Date string
Rates map[string]float64
}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
log.Fatal(err)
}
打印相应的值:
if r, ok := data.Rates["USD"]; ok {
log.Println("Rate", r)
} else {
log.Println("no rate")
}
完整示例:点击这里
英文:
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")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论