Pgx: How to convert pgx.Rows from Query() to json array?

Created on 8 May 2018  路  1Comment  路  Source: jackc/pgx

I tried func for sql.Rows, but it doesn't work for pgx.Rows

```
func PgSqlRowsToJson(rows *pgx.Rows) []byte {
fieldDescriptions := rows.FieldDescriptions()
var columns []string
for _, col := range fieldDescriptions {
columns = append(columns, col.Name)
}

count := len(columns)
tableData := make([]map[string]interface{}, 0)
values := make([]interface{}, count)
valuePtrs := make([]interface{}, count)
for rows.Next() {
    for i := 0; i < count; i++ {
        valuePtrs[i] = &values[i]
    }
    rows.Scan(valuePtrs...)
    entry := make(map[string]interface{})
    for i, col := range columns {
        var v interface{}
        val := values[i]
        b, ok := val.([]byte)
        if ok {
            v = string(b)
        } else {
            v = val
        }
        entry[col] = v
    }
    tableData = append(tableData, entry)
}
jsonData, _ := json.Marshal(tableData)

return jsonData

}
```
The problem is that Scan() doesn't work with interface{} and it works with explicitly defined types only.
Can you help me how to fix it?

Most helpful comment

Rows.Values should be easier to work with when you are dealing with arbitrary rows where you don't know the number of type of columns ahead of time.

Beyond that, consider building the JSON in PostgreSQL. Much simpler Go code and quite possibly superior performance as well. This article is slightly dated but it covers the basics of the SQL.

>All comments

Rows.Values should be easier to work with when you are dealing with arbitrary rows where you don't know the number of type of columns ahead of time.

Beyond that, consider building the JSON in PostgreSQL. Much simpler Go code and quite possibly superior performance as well. This article is slightly dated but it covers the basics of the SQL.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

badoet picture badoet  路  10Comments

pengux picture pengux  路  3Comments

bernhardreiter picture bernhardreiter  路  7Comments

hgl picture hgl  路  6Comments

jeromer picture jeromer  路  5Comments