Dumping MySQL tables to JSON with Golang

后端 未结 6 1997
余生分开走
余生分开走 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:39

    I also needed to dump database tables to json and here is how I achieved: (different than another answer in this topic, everything is not string, thanks to this answer: https://stackoverflow.com/a/17885636/4124416, I could get integer fields correctly)

    func getJSON(sqlString string) (string, error) {
        rows, err := db.Query(sqlString)
        if err != nil {
            return "", err
        }
        defer rows.Close()
        columns, err := rows.Columns()
        if err != nil {
            return "", err
        }
        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, err := json.Marshal(tableData)
        if err != nil {
            return "", err
        }
        fmt.Println(string(jsonData))
        return string(jsonData), nil 
    }
    

    Here is a sample output:

    [{"ID":0,"Text":"Zero"},{"ID":1,"Text":"One"},{"ID":2,"Text":"Two"}]
    

提交回复
热议问题