json - 在 Golang 中打印解码后的 JSON

标签 json go struct io printf

总的来说,我对 Go/编程还很陌生 - 刚刚开始学习它,同时忙于创建我自己的加密货币投资组合网站。

我正在努力打印到网络服务器输出。如果我使用 Printf - 它会打印到控制台,但是一旦我使用 Fprintf 打印到 Web 应用程序,我就会收到一些我似乎无法解决的错误。

有人可以指导我完成它吗?

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)

与:

fmt.Fprintf("%+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)

关于json - 在 Golang 中打印解码后的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46760795/

相关文章:

javascript - 将状态数组值转换为键值对

json - 将 JSON 数据传递给 Swift 中的标签

javascript - 为什么 SoundCloud API 会导致循环以不同的顺序列出数据

matlab - MATLAB 中结构的高效索引

c++ - 使用外部函数获取和设置嵌套结构的值

java - 如何将字符串转换为 JsonObject

networking - 如何从本地接口(interface)获取所有地址和掩码?

go - 在动态结构函数 Golang 中修改结构值

go - kubernetes golang客户端:在容器中获取容器

c - 如何将结构添加到结构数组的末尾?