我正在使用github.com/jackc/pgxpostgreSQL 进行工作。不,我想将 pgx.Rows 从 Query() 转换为 json 数组。我尝试了 func *sql.Rows,但它不起作用*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
}
Run Code Online (Sandbox Code Playgroud)
问题是它Scan()不适用于interface{}并且仅适用于显式定义的类型。你能帮我解决这个问题吗?
您可以使用pgx.FieldDescriptionsType方法来检索列的预期类型。将其传递给reflect.New您,然后可以分配一个指向该类型值的指针,并且使用这些新分配的值,您可以制作一个非零切片,interface{}s其基础值具有预期类型。
例如:
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
}
Run Code Online (Sandbox Code Playgroud)