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

Time:2020-4-1

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]
      }
      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: for JSON operation, here are some more practical JSON online tools for your reference:

On-lineJSONCode inspection, inspection, beautification and formatting tools:
http://tools.jb51.net/code/json

JSONOnline formatting tool:
http://tools.jb51.net/code/jsonformat

Online XML/JSONMutual conversion tools:
http://tools.jb51.net/code/xmljson

jsonCode online formatting / beautifying / compression / editing / conversion tool:
http://tools.jb51.net/code/jsoncodeformat

On-linejsonCompression / escape tool:
http://tools.jb51.net/code/json_yasuo_trans

C language style / HTML / CSS/jsonCode formatting beautification tool:
http://tools.jb51.net/code/ccode_html_css_json

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 […]