A method to output SQL result set in JSON format by golang


In this paper, an example is given to show how to output SQL result set in JSON format in golang. To share with you for your reference, as follows:

Copy codeThe code is as follows:
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]
      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
    return string(jsonData), nil

PS: for JSON operation, here are some more practical JSON online tools for your reference:

On-lineJSONCode inspection, inspection, beautification and formatting tools:

JSONOnline formatting tool:

Online XML/JSONMutual conversion tools:

jsonCode online formatting / beautifying / compression / editing / conversion tool:

On-linejsonCompression / escape tool:

C language style / HTML / CSS/jsonCode formatting beautification tool:

I hope that this paper will be helpful for you to design the go language program.

Recommended Today

Python basics Chinese series tutorial · translation completed

Original: Python basics Python tutorial Protocol: CC by-nc-sa 4.0 Welcome anyone to participate and improve: a person can go very fast, but a group of people can go further. Online reading Apache CN learning resources catalog introduce Seven reasons to learn Python Why Python is great Learn Python introduction Executing Python scripts variable character string […]