Dumping MySQL tables to JSON with Golang

后端 未结 6 1952
余生分开走
余生分开走 2021-01-31 10:18

Was putting together a quick dumper for MySQL to JSON in Go. However I find that everything that I retrieve from the database is a []byte array. Thus instead of n

6条回答
  •  迷失自我
    2021-01-31 10:53

    you can dump the table into json just fine, however everything will be string :(

    q := "select * from table"
    debug("SQL: %s", q)
    
    rows, err := db.Query(q)
    checkError(err)
    defer rows.Close()
    
    columns, err := rows.Columns()
    checkError(err)
    
    scanArgs := make([]interface{}, len(columns))
    values := make([]interface{}, len(columns))
    
    for i := range values {
        scanArgs[i] = &values[i]
    }
    
    for rows.Next() {
        err = rows.Scan(scanArgs...)
        checkError(err)
    
        record := make(map[string]interface{})
    
        for i, col := range values {
            if col != nil {
                record[columns[i]] = fmt.Sprintf("%s", string(col.([]byte)))
            }
        }
    
        s, _ := json.Marshal(record)
        fmt.Printf("%s\n", s)
    }
    

提交回复
热议问题