douchen4915 2016-06-29 07:26
浏览 52
已采纳

结果打印空的Json [重复]

This question already has an answer here:

I am trying to retrieve some data from my postgres db and printing them to localhost/db as json. I am succeeding in printing them without json but I need them in json.

main.go:

package main

import (
    "database/sql"
    "encoding/json"
    "fmt"
    "log"
    "net/http"

    _ "github.com/lib/pq"
)

type Book struct {
    isbn   string
    title  string
    author string
    price  float32
}

var b []Book

func main() {

    db, err := sql.Open("postgres", "postgres://****:****@localhost/postgres?sslmode=disable")

    if err != nil {
        log.Fatal(err)
    }
    rows, err := db.Query("SELECT * FROM books")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    var bks []Book
    for rows.Next() {
        bk := new(Book)
        err := rows.Scan(&bk.isbn, &bk.title, &bk.author, &bk.price)
        if err != nil {
            log.Fatal(err)
        }
        bks = append(bks, *bk)
    }
    if err = rows.Err(); err != nil {
        log.Fatal(err)
    }

    b = bks

    http.HandleFunc("/db", getBooksFromDB)
    http.ListenAndServe("localhost:1337", nil)

}

func getBooksFromDB(w http.ResponseWriter, r *http.Request) {

    fmt.Println(b)
    response, err := json.Marshal(b)
    if err != nil {
        panic(err)

    }

    fmt.Fprintf(w, string(response))
}

This is what I get when I access localhost:1337/db

And this is the output on the terminal:

 [{978-1503261969 Emma Jayne Austen 9.44} {978-1505255607 The Time Machine H. G. Wells 5.99} {978-1503379640 The Prince Niccolò Machiavelli 6.99}]

Anyone knows what is the problem?

</div>
  • 写回答

1条回答 默认 最新

  • dongtun1872 2016-06-29 07:32
    关注

    The encoding/json package uses reflection (reflect package) to access fields of structs. You need to export the fields of your struct to make it work (start them with an uppercase letter):

    type Book struct {
        Isbn   string
        Title  string
        Author string
        Price  float32
    }
    

    And when scanning:

    err := rows.Scan(&bk.Isbn, &bk.Title, &bk.Author, &bk.Price)
    

    Quoting from json.Marshal():

    Struct values encode as JSON objects. Each exported struct field becomes a member of the object...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)