从SQL结果创建用于API的JSON。

huangapple go评论94阅读模式
英文:

Create JSON from SQL result for API

问题

我很新手Go语言,希望这个问题很简单。我想从SQL数据库的行中构建一个JSON值。它不一定是SQL,但我正在寻找一种生成结构体列表或容器的方法,以便从中生成JSON。

例如,对"/post"的HTTP GET请求将返回:

{
"posts": [
{ "title": "第一个标题", "created_by": "User1" },
{ "title": "我的第二篇文章", "created_by": "User1" }
]
}

我不知道正确的做法是什么。我尝试过其他方法,使用指针数组,但结果不正确。到目前为止,它打印出每个结构体的正确值,但生成的Marshal结果为空[{},{},{}]

请对我温柔点 从SQL结果创建用于API的JSON。

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\n", 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\n", data)
}
英文:

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 从SQL结果创建用于API的JSON。

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\n", 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\n", data)
}

答案1

得分: 1

你的字段没有被导出,所以json包无法看到它们。

请参阅50 Shades of Go获取更详细的解释和其他常见的陷阱。

英文:

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.

huangapple
  • 本文由 发表于 2016年3月3日 01:18:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/35753957.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定