doujia4619 2016-03-02 17:18 采纳率: 0%
浏览 37
已采纳

从SQL结果为API创建JSON

I'm very new to Go so hopefully this is simple to fix. I want to build a JSON value from rows in an SQL database. It doesn't have to be SQL but I'm looking for a way to generate a list of structs or a container that holds many values in order to generate JSON from it.

For example, an HTTP GET request to "/post" would return:

{
  "posts": [
    { "title": "First title", "created_by": "User1" },
    { "title": "My second post", "created_by": "User1"}
  ]
}

I don't know what's the proper way to do this. I've tried other ways using an array of pointers but it doesn't come out correctly. So far it prints out the correct values for each struct but the resulting Marshal is empty [{},{},{}]

Please go easy on me :)

example.go

package main

import (
    "fmt"
    "encoding/json"
    "time"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)


type Post struct {
    name string `json:"name"`
    created_by string `json:"created_by"`
    created_at time.Time `json:"created_at"`
}

type Posts []Post

func main() {

    db, err := sql.Open("mysql", "root:1234@/blog?parseTime=true")
    if err != nil { panic(err.Error()) }
    defer db.Close()

    err = db.Ping()
    if err != nil { panic(err.Error()) }

    rows, err := db.Query("select title, created_by, created_at from post")
    if err != nil { panic(err.Error()) }
    defer rows.Close()

    var posts Posts
    for rows.Next() {            
        var post Post
        err := rows.Scan(&post.name, &post.created_by, &post.created_at)
        if err != nil { panic(err.Error()) }
        fmt.Printf("name=%s, created_by=%s, created_at=%s
", post.name, post.created_by, post.created_at)
        posts = append(posts, post)                  
    }    

    data, err := json.Marshal(posts)    
    if err != nil { panic(err.Error()) }
    fmt.Printf("%s
", data)
}
  • 写回答

1条回答 默认 最新

  • dongzanghua8422 2016-03-02 17:27
    关注

    Your fields aren't exported, so the json package can't see them.

    See 50 Shades of Go for a longer explanation and others common gotchas.

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

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献