golang implements the sql result set output in json format

  • 2020-06-07 04:36:49
  • OfStack

This article gives an example of how golang implements sql result set output in json format. To share for your reference, specific 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]
      }
      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
}

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

Online JSON code inspection, inspection, beautification, formatting tools:
http://tools.ofstack.com/code/json

JSON online formatting tools:
http://tools.ofstack.com/code/jsonformat

Online XML/JSON interconversion tool:
http://tools.ofstack.com/code/xmljson

json code online formatting/beautification/compression/editing/conversion tools:
http://tools.ofstack.com/code/jsoncodeformat

Online json compression/escape tool:
http://tools.ofstack.com/code/json_yasuo_trans

C language style /HTML/CSS/json code Formatting tool:
http://tools.ofstack.com/code/ccode_html_css_json

I hope that this article has been helpful in Go language programming.


Related articles: