如何使用Golang将SQL行以JSON格式打印出来?

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

How do I print sql rows in JSON using golang?

问题

你可以使用json.MarshalIndent函数来格式化输出JSON。这个函数可以将JSON数据转换为带缩进和换行符的格式,使其更易读。你可以将json.Marshal(users)替换为json.MarshalIndent(users, "", " "),其中users是你要转换为JSON的数据,""是前缀字符串," "是缩进字符串。这样输出的JSON将会更加可读。

修改后的代码如下:

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)
	jsonBytes, _ := json.MarshalIndent(users, "", "    ")
	fmt.Println(string(jsonBytes))
}

func main() {
	PostgresTest()
}

这样你就可以在开发过程中打印出格式化的JSON或JSON列表了。

英文:

I understand how to return JSON using the gorilla/mux go package but i want to be able to print JSON also in development without having to wrap it to route endpoint

I have the following code and want to list users from postgresql database

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

here is what am expecting

[
    {
        "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"
    }
]

but here is what am getting

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

What do i do to be able to print JSON or list of JSON?

答案1

得分: 2

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包的文档,其中可以找到如何美化格式JSON的方法。

英文:

json.Marshal function returns []byte thus what you see in the output is a decimal representation of each byte from your JSON result. You must convert []byte returned by json.Marshal to string either directly like this

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

or by using formatter

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

I also advise you to read encoding/json package documentation when you can find how to pretty format JSON.

答案2

得分: 0

使用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}
英文:

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

Here is the output, the string(js) converts to JSON

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

huangapple
  • 本文由 发表于 2021年9月7日 03:24:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/69079450.html
匿名

发表评论

匿名网友

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

确定