callfunc
callfunc

Reputation: 31

Wants to generate json output from mysql using gorm in Go

So I am trying to get data from my database i.e MySQL. I am able to finish that step accessing the database but, the problem is I want to get the output in JSON format, but i did some research but didn't got the result so anyone can guide or hep me in this, getting the MySQL data in json by using GORM. Here is the sample of my code which i written.

package main

import (
    "fmt"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql" //This must be introduced! !
)

type k_movie struct {
    Id         uint32
    Title      string `gorm:"default:''"`
    Url_name   string `gorm:"default:''"`
    K_score    string ``
    Poster_url string ``
}

func main() {

    db, errDb := gorm.Open("mysql", "root:xyz@123@(127.0.0.1)/dbdump?charset=utf8mb4&loc=Local")

    if errDb != nil {
        fmt.Println(errDb)
    }
    defer db.Close() //Close the database connection after use up

    db.LogMode(true) //Open sql debug mode

    //SELECT * FROM `k_movies`  WHERE (id>0 and id<.....)
    var movies []k_movie
    db.Where("id>? and id<?", 0, 103697).Limit(3).Find(&movies)
    fmt.Println(movies)

    //Get the number
    total := 0
    db.Model(&k_movie{}).Count(&total)
    fmt.Println(total)

    var infos []k_movie //Define an array to receive multiple results
    db.Where("Id in (?)", []uint32{1, 2, 3, 4, 5, 6, 7, 8}).Find(&infos)
    fmt.Println(infos)
    fmt.Println(len(infos)) //Number of results

    var notValue []k_movie
    db.Where("id=?", 3).Find(&notValue)
    if len(notValue) == 0 {
        fmt.Println("No data found!")
    } else {
        fmt.Println(notValue)
    }

}

And the output I'm getting in this format.

kumardivyanshu@Divyanshus-MacBook-Air ~/myproject/src/github.com/gorm_mysql % go run test.go

(/Users/kumardivyanshu/myproject/src/github.com/gorm_mysql/test.go:31) 
[2021-05-13 08:59:45]  [3.89ms]  SELECT * FROM `k_movies`  WHERE (id>0 and id<103697) LIMIT 3  
[3 rows affected or returned ] 
[{1 Golmaal: Fun Unlimited golmaal-fun-unlimited 847 https://movieassetsdigital.sgp1.cdn.digitaloceanspaces.com/thumb/32b7385e1e616d7ba3d11e1bee255ecce638a136} {2 Dabangg 2 dabangg-2 425 https://movieassetsdigital.sgp1.cdn.digitaloceanspaces.com/thumb/1420c4d6f817d2b923cd8b55c81bdb9d9fd1eca0} {3 Force force 519 https://movieassetsdigital.sgp1.cdn.digitaloceanspaces.com/thumb/cd1dc247da9d16e194f4bfb09d99f4dedfb2de00}]

(/Users/kumardivyanshu/myproject/src/github.com/gorm_mysql/test.go:36) 
[2021-05-13 08:59:45]  [20.22ms]  SELECT count(*) FROM `k_movies`    
[0 rows affected or returned ] 
103697

(/Users/kumardivyanshu/myproject/src/github.com/gorm_mysql/test.go:40) 
[2021-05-13 08:59:45]  [2.32ms]  SELECT * FROM `k_movies`  WHERE (Id in (1,2,3,4,5,6,7,8))  
[8 rows affected or returned ] 
[{1 Golmaal: Fun Unlimited golmaal-fun-unlimited 847 https://movieassetsdigital.sgp1.cdn.digitaloceanspaces.com/thumb/32b7385e1e616d7ba3d11e1bee255ecce638a136} {2 Dabangg 2 dabangg-2 425 https://movieassetsdigital.sgp1.cdn.digitaloceanspaces.com/thumb/1420c4d6f817d2b923cd8b55c81bdb9d9fd1eca0} {3 Force force 519 https://movieassetsdigital.sgp1.cdn.digitaloceanspaces.com/thumb/cd1dc247da9d16e194f4bfb09d99f4dedfb2de00} {4 Eega eega 906 https://movieassetsdigital.sgp1.cdn.digitaloceanspaces.com/thumb/08aef7d961d4699bf2d12a7c854b6b32d1445247} {5 Fukrey fukrey 672 https://movieassetsdigital.sgp1.cdn.digitaloceanspaces.com/thumb/5d14bd2fb0166f4bb9ab919e31b69f2605f366aa} {6 London Paris New York london-paris-new-york 323 https://movieassetsdigital.sgp1.cdn.digitaloceanspaces.com/thumb/222d8a6b5c76b1d3cfa0b93d4bcf1a1f16f5e199} {7 Bhaag Milkha Bhaag bhaag-milkha-bhaag 963 https://movieassetsdigital.sgp1.cdn.digitaloceanspaces.com/thumb/efa8b86c753ae0110cc3e82006fadabb06f1486c} {8 Bobby Jasoos bobby-jasoos 244 https://movieassetsdigital.sgp1.cdn.digitaloceanspaces.com/thumb/0e9540d4c962ec33d8b63c0c563e7b64169122e0}]
8

(/Users/kumardivyanshu/myproject/src/github.com/gorm_mysql/test.go:45) 
[2021-05-13 08:59:45]  [1.56ms]  SELECT * FROM `k_movies`  WHERE (id=3)  
[1 rows affected or returned ] 
[{3 Force force 519 https://movieassetsdigital.sgp1.cdn.digitaloceanspaces.com/thumb/cd1dc247da9d16e194f4bfb09d99f4dedfb2de00}]

Upvotes: 0

Views: 1040

Answers (1)

Chen A.
Chen A.

Reputation: 11280

You need to define the json tag on your struct, so you can use the json.Marshal to grab a []byte slice that presents a json object.

Example taken from Go by example:

type Response2 struct {
  Page   int      `json:"page"`
  Fruits []string `json:"fruits"`
}

res2D := &Response2{
    Page:   1,
    Fruits: []string{"apple", "peach", "pear"}}
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B))
That would print:

{"page":1,"fruits":["apple","peach","pear"]} 

Upvotes: 1

Related Questions