打印空Json结果 [英] Printing Empty Json as a result

查看:125
本文介绍了打印空Json结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的postgres数据库中检索一些数据,并以json的形式打印到 localhost / db 。我成功打印他们没有json,但我需要他们在json。

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

这是当我访问localhost时获得的:1337 / db

这是终端的输出:

 [{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?

推荐答案

encoding / json 包使用反射( 反映 包)以访问结构体的字段。您需要导出结构体的字段以使其工作(以大写字母开头):

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
}

扫描时:

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

json.Marshal()


结构值编码为JSON对象。每个导出的结构域成为对象的成员...

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

这篇关于打印空Json结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆