【问题标题】:How do I print sql rows in JSON using golang?如何使用 golang 在 JSON 中打印 sql 行?
【发布时间】:2021-11-03 20:00:03
【问题描述】:

我了解如何使用 gorilla/mux go 包返回 JSON,但我希望能够在开发中也打印 JSON,而不必将其包装到路由端点

我有以下代码,想列出 postgresql 数据库中的用户

package main

import (
    "encoding/json"
    "fmt"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

var DB *gorm.DB
var err error


const DNS = "host=localhost user=postgres_user password=postgres_password dbname=postgres_db port=5432 sslmode=disable"


type User struct {
    gorm.Model
    FirstName string `json:"firstname"`
    LastName  string `json:"lastname"`
    Email     string `json:"email"`
}

func PostgresTest() {
    DB, err = gorm.Open(postgres.Open(DNS), &gorm.Config{})
    if err != nil {
        fmt.Println(err.Error())
        panic("Cannot connect to DB")
    }
    
    var users []User
    
    DB.Limit(2).Find(&users)
    // json.NewEncoder(w).Encode(users)
    fmt.Println(json.Marshal(users))

}

func main() {
    PostgresTest()
}

这就是我们所期待的

[
    {
        "ID": 1,
        "CreatedAt": "2021-09-06T14:18:47.766414-05:00",
        "UpdatedAt": "2021-09-06T14:18:47.766414-05:00",
        "DeletedAt": null,
        "firstname": "first1",
        "lastname": "last1",
        "email": "first1.last1@email.com"
    },
    {
        "ID": 2,
        "CreatedAt": "2021-09-06T14:18:58.144181-05:00",
        "UpdatedAt": "2021-09-06T14:18:58.144181-05:00",
        "DeletedAt": null,
        "firstname": "first2",
        "lastname": "last2",
        "email": "first2.last2@email.com"
    }
]

这就是我得到的结果

[91 123 34 73 68 34 58 49 44 34 67 114 101 97 116 101 100 65 116 34 58 34 50 48 50 49 45 48 57 45 48 54 84 48 55 58 50 49 58 49 51 46 53 52 50 54 55 50 45 48 53 58 48 48 34 44 34 85 112 100 97 116 101 100 65 116 34 58 34 50 48 50 49 45 48 57 45 48 54 84 48 55 58 50 49 58 49 51 46 53 52 50 54 55 50 45 48 53 58 48 48 34 44 34 68 101 108 101 116 101 100 65 116 34 58 110 117 108 108 44 34 102 105 114 115 116 110 97 109 101 34 58 34 98 97 98 97 116 117 110 100 101 34 44 34 108 97 115 116 110 97 109 101 34 58 34 98 117 115 97 114 105 34 44 34 101 109 97 105 108 34 58 34 98 98 117 115 97 114 105 64 101 109 97 105 108 46 99 111 109 34 125 93] <nil>

如何才能打印 JSON 或 JSON 列表?

【问题讨论】:

    标签: json postgresql go go-gorm


    【解决方案1】:

    json.Marshal 函数返回 []byte,因此您在输出中看到的是 JSON 结果中每个字节的十进制表示。您必须像这样直接将json.Marshal 返回的[]byte 转换为字符串

    jsonUsers, err := json.Marshal(users)
    if err != nil {
      log.Fatal(err)
    }
    fmt.Println(string(jsonUsers))
    

    或使用格式化程序

    jsonUsers, err := json.Marshal(users)
    if err != nil {
      log.Fatal(err)
    }
    fmt.Printf("%s", jsonUsers)
    

    我还建议您阅读 encoding/json 包文档,当您可以找到如何使用 pretty format JSON 时。

    【讨论】:

    • 是json.Marshal 的选择吗?你提到的漂亮格式怎么样?我使用json.Marshal 只是尝试不同的东西,所以如果有更好的方法,答案不必使用它
    • fmt.Println(string(json.Marshal(users)) 和 fmt.Printf("%s", json.Marshal(users)) 都返回 ./main.go:39:33: multiple-value json.Marshal() in single-value context
    • 对不起,我的错误,我更新了答案。至于替代方法,我认为在您的情况下json.Marshal 很好。您可以在其中创建编码器/解码器的版本,它适用于 io.Reader / io.Writer。至于漂亮的打印,您可以将json.Marshal 替换为json.MarshalIndent。
    • 对于json.MarshalIndent 正在获取not enough arguments in call to json.MarshalIndent have ([]User) want (interface {}, string, string)
    • 请阅读json.MarshalIndent的文档。
    【解决方案2】:

    使用string(jsonbytecode)

    type B struct {
        C int
        D int
    }
        
    func main() {
        b := B{C: 4, D: 5}
        js, _ := json.Marshal(b)
        fmt.Println(js)
        fmt.Println(string(js))
    }
    

    这是输出,string(js) 转换为 JSON

    [123 34 67 34 58 52 44 34 68 34 58 53 125]
    {"C":4,"D":5}
    

    【讨论】:

    • 感谢您的回答。你介意用我的代码来给出答案吗?似乎您创建了另一个示例,而我已经声明了要使用的代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 2020-08-13
    相关资源
    最近更新 更多