Sviatoslav
Sviatoslav

Reputation: 1312

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

I'm using github.com/jackc/pgx for work with postgreSQL. Noq I want to convert pgx.Rows from Query() to json array. 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?

Upvotes: 7

Views: 4676

Answers (1)

mkopriva
mkopriva

Reputation: 38203

You can use the pgx.FieldDescription's Type method to retrieve a column's expected type. Passing that to reflect.New you can then allocate a pointer to a value of that type, and with these newly allocated values you can then make a slice of non-nil interface{}s whose underlying values have the expected type.

For example:

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)

    valuePtrs := make([]interface{}, count)
    for rows.Next() {
        for i := 0; i < count; i++ {
            valuePtrs[i] = reflect.New(fieldDescriptions[i].Type()).Interface() // allocate pointer to type
        }
        rows.Scan(valuePtrs...)

        entry := make(map[string]interface{})
        for i, col := range columns {
            var v interface{}
            val := reflect.ValueOf(valuePtrs[i]).Elem().Interface() // dereference pointer
            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
}

Upvotes: 6

Related Questions