GO:格式化sql输出到json

时间:2016-01-04 02:57:56

标签: go

我有一个查询数据库并返回两列的GO函数:

var colA string
var colB string

    err = db.QueryRow("select colA, colB from table where colA = %v", 1).Scan(&colA,&colB)
    if err != nil {
        fmt.Printf(err.Error())
    }
    fmt.Println(colA,colB)

    return nil

我想以json格式返回输出,如{colA:colB}。我玩过json.Marshal函数,但无法正常工作。我可能在这里错过了一些非常简单的东西......

4 个答案:

答案 0 :(得分:1)

如果你知道你的数据是什么,你可以创建一个结构:例如

type User struct {
    Username string `json:"username"`
    Email    string `json:"email"`
}

然后查询:

user := User{}
err = db.QueryRow("select colA, colB from table where colA = %v", 1).Scan(&user.Username,&user.Email)
    if err != nil {
        fmt.Printf(err.Error())
}

然后打电话给marshal

msg, err := json.Marshal(user)
if err != nil {
    log.Println(err)
}

fmt.Println(string(msg)) // "{ "username": "Blah", "email": "asd@asd.com" }"

如果您在json.Marshal上呼叫Marshal,则使用struct包也必须使用字段名称上的大写首字母输出您的字段,例如Username

  

//此包将忽略该字段。字段int json:"-"

     

//字段在JSON中显示为键“myName”。字段int json:"myName"

     

//字段在JSON中显示为键“myName”,//字段被省略   如果对象的值为空,则来自对象//如上所定义。 Field int   json:"myName,omitempty"

     

//字段在JSON中显示为键“字段”(默认值),但是//   如果为空,则跳过该字段。 //注意引导逗号。 Field int   json:",omitempty"

https://golang.org/pkg/encoding/json/#Marshal

答案 1 :(得分:0)

您可以创建一个元素地图并编组:

m := map[string]string{colA: colB}
b, err := json.Marshal(m)

完整示例:https://play.golang.org/p/ntT5h3oHvY

答案 2 :(得分:0)

我建议调查一些数据库管理框架。

我个人使用gorm(github.com/jinzhu/gorm)来满足我的数据库需求。它具有使用结构自动创建数据库并再次解析它们的功能。

您可以将其与" encoding / json"配对。包将它带到/从json进出数据库。

这里有一些您可以用作参考的个人代码:

Struct

type Application struct {
  Id            int64           `json:"id"`
  UserID        int64           `sql:"not null;" json:"user_id"`
  Name          string          `sql:"size:255; not null; unique;" json:"name"`
  ExposedPorts  string          `json:"exposed_ports"` //docker
  DockerImage   string          `sql:"size:255; not null;" json:"docker_image"`
  Dependencies  string          `json:"dependencies"`  
  IsEnabled     bool            `sql:"default:true" json:"is_enabled"`

}

JSON:

func (a *Application) GetJSON() (string, error) {
    b, err := json.Marshal(a)
    if err != nil {
        logging.Log(err)
        return "",err;
    }
    return string(b),err;
}

Database

    //Get application information
func GetApplication(id int64) (*models.Application, error) {
 app := &models.Application{}

 err := db.Where(&models.Application{Id: id}).First(&app).Error

 return app, err
}

func GetApplications() ([]models.Application, error) {
    //Returns a list of all applications 
    apps := []models.Application{}

    err := db.Find(&apps).Error

    return apps, err
}

//delete application from database
func DeleteApplication(id int64) (bool, error) {
    logging.Log("Deleting Application: ", id)

    app := models.Application{}

    err := db.Where(&models.Application{Id: id}).First(&app).Error 

    if err != nil {
        return false, err
    }
    //  TODO: Check for auth
    //      Delete all containers

    //Delete application from database
    err = db.Delete(&app).Error

    if err != nil {
       return false, err
    }

    return true, err

}

//Update Application
func UpdateApplication(app *models.Application) (bool, error) {

    newapp := models.Application{}
    err := db.Where(&models.Application{Id: app.Id}).First(&newapp).Error 

    if err != nil {
       return false, err
    }

    err = db.Save(&app).Error

    if err != nil {
        return false, err
    }

    return true, nil
} 

希望这会有所帮助:)

答案 3 :(得分:0)

这里是一个完整的示例:

campaign.model.go

package models

import "database/sql"

// Campaign Model
type Campaign struct {
    CampaignId int `db:"campaign_id" json:"campaignId"`
    CampaignNme string `db:"campaign_nme" json:"campaignNme"`
    OrganizationId sql.NullInt64 `db:"organization_id" json:"organizationId"`
}

campaign.repository.go

package repositories

import (
    "github.com/jmoiron/sqlx"
    "go-clean-arch/domain/models"
    "go-clean-arch/domain/repositories"
)

type CampaignRepository struct {
    Db *sqlx.DB
}

func NewCampaignRepository(Db *sqlx.DB) repositories.CampaignRepository {
    return &CampaignRepository{Db}
}

func (cr *CampaignRepository)FindById(id string) (models.Campaign, error) {
    campaign := models.Campaign{}
    query := `
        SELECT
            campaign_id,
            campaign_nme,
            organization_id
        FROM "CAMPAIGN" WHERE campaign_id = $1
    `
    err := cr.Db.Get(&campaign, query, id)
    if err != nil {
        return campaign, err
    }
    return campaign, nil
}

main.go

func main() {
    dbConf := database.PGDatabaseConfig{
        Host: viper.GetString("SQL_HOST"),
        Port: viper.GetString("SQL_PORT"),
        User: viper.GetString("SQL_USER"),
        Password: viper.GetString("SQL_PASSWORD"),
        Dbname: viper.GetString("SQL_DB"),
    }
    db, err := database.ConnectPGDatabase(&dbConf)
    if err != nil {
        log.Fatal(err)
    }

    defer func () {
        if err := recover(); err != nil {
            fmt.Println(err)
        }
    }()

    //userRepository := repositories.NewUserRepository(db)
    //users, _ := userRepository.FindAll()
    //fmt.Printf("%#v", &users)

    campaignRepository := repositories.NewCampaignRepository(db)
    campaign, err := campaignRepository.FindById("102")
    if err != nil {
        panic(err)
    }
    fmt.Printf("%#v", campaign)
    campaignJSON, err := json.Marshal(campaign)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(campaignJSON))

}

输出:

☁  go-clean-arch [master] ⚡  go run main.go
models.Campaign{CampaignId:102, CampaignNme:"Generic Party / Memories", OrganizationId:sql.NullInt64{Int64:0, Valid:false}}
campaignJSON: {"campaignId":102,"campaignNme":"Generic Party / Memories","organizationId":{"Int64":0,"Valid":false}}