golang: 把sql结果集以json格式输出

代码出处:http://stackoverflow.com/questions/19991541/dumping-mysql-tables-to-json-with-golang

func getJSON(sqlString string) (string, error) {
	stmt, err := db.Prepare(sqlString)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()
	rows, err := stmt.Query()
	if err != nil {
		return nil, 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 
}


你可能感兴趣的:(go)