Said  Saifi Said Saifi - 1 year ago 36
JSON Question

Printing Empty Json as a result

I am trying to retrieve some data from my postgres db and printing them to

as json. I am succeeding in printing them without json but I need them in json.


package main

import (

_ ""

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 {
rows, err := db.Query("SELECT * FROM books")
if err != nil {
defer rows.Close()

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

b = bks

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


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

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


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?

Answer Source

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...