A
A
anonymon2018-01-31 12:05:12
MySQL
anonymon, 2018-01-31 12:05:12

Golang how to generate json from db records?

Good afternoon, I can't figure out how to get one big JSON from DB records.
Code Example

type Statistic struct {
  usernumber 		 string
  timestamp 		 string
  holdtime 		    string
  position 		    string
  queue 		    string
  originalposition       string
  active 		    string
  agent 		    string
}

rows, err := dbStat.Query("SELECT usernumber, timestamp, holdtime, queue, position, originalposition, active, agent FROM datatable ORDER BY created_at desc")
if err != nil{
  log.Println(err)
}
defer rows.Close()

stats := make([]*Statistic, 0)

for rows.Next() {
    
    bk := new(Statistic)
    err := rows.Scan(&bk.usernumber, &bk.timestamp, &bk.holdtime, &bk.queue, &bk.position, &bk.originalposition, &bk.active, &bk.agent)	        
    if err != nil { log.Fatal(err) }
    
    stats = append(stats, bk)

    for _, bk := range stats {

    fmt.Println(bk.agent)

    // тут была передача нужных значений дальше в методы
    // теперь нужно сформировать один JSON со всеми значениями
    }
}

It turns out to sort through the values ​​​​and form one json at a time, but it’s impossible to get one json with all the values, I don’t even know how to google it and where to dig.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Tsvetkov, 2018-01-31
@anonymon

After the loop, you need to convert stats to json
. But the Statistic structure does not have exportable fields, so this will not work. It is necessary to make the fields of the structure exportable, that is, to describe them with a capital letter

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question