在Golang中打印解码的JSON
一般来说,我是一个新手/编程新手——刚刚开始学习,正在忙于创建自己的加密货币投资组合网站 我正在努力打印到web服务器输出。如果我使用Printf,它会打印到控制台,但一旦我使用Fprintf打印到web应用程序,我就会收到一些我似乎无法解决的错误 有人能陪我走过吗在Golang中打印解码的JSON,json,go,struct,io,printf,Json,Go,Struct,Io,Printf,一般来说,我是一个新手/编程新手——刚刚开始学习,正在忙于创建自己的加密货币投资组合网站 我正在努力打印到web服务器输出。如果我使用Printf,它会打印到控制台,但一旦我使用Fprintf打印到web应用程序,我就会收到一些我似乎无法解决的错误 有人能陪我走过吗 package main import ( "encoding/json" "fmt" "log" "net/http" ) type Obsidian []str
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type Obsidian []struct {
PriceUsd string `json:"price_usd"`
PriceBtc string `json:"price_btc"`
}
func webserver(w http.ResponseWriter, r *http.Request) {
url := "https://api.coinmarketcap.com/v1/ticker/obsidian/"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatal("NewRequest: ", err)
return
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal("Do: ", err)
return
}
defer resp.Body.Close()
var record Obsidian
if err := json.NewDecoder(resp.Body).Decode(&record); err != nil {
log.Println(err)
}
fmt.Printf("%+v", record)
}
func main() {
http.HandleFunc("/test", webserver)
http.ListenAndServe(":8001", nil)
}
我试图替换:
fmt.Printf("%+v", record)
与:
并接收以下错误:
./test.go:54:21: cannot use "%+v" (type string) as type io.Writer in argument to fmt.Fprintf:
string does not implement io.Writer (missing Write method)
./test.go:54:21: cannot use record (type Obsidian) as type string in argument to fmt.Fprintf
感谢@milochristiansen
fmt.Fprintf(w, "%+v", record)
感谢@milochristiansen
fmt.Fprintf(w, "%+v", record)
你也可以使用
w.Write([]byte(record))
你也可以使用
w.Write([]byte(record))
fmt.Fprintf(w,“%+v”,record)
应该能帮你解决问题。@MiloChristiansen花了几个小时试图解决这个问题,你把它分到了不到5个等级!非常感谢fmt.Fprintf(w,“%+v”,record)
应该能帮你解决这个问题。@MiloChristiansen花了几个小时试图解决这个问题,你把它整理成了不到5个!谢谢