doulizhi1247 2017-03-13 22:19
浏览 327
已采纳

如何在Golang中将* sql.Rows转换为键入的JSON

Essentially, I am trying to run a query on a MySQL database, get the data made converted into JSON and sent back to the client. I have tried several methods and all of the "easy" ones result in sending back all of the JSON as a string. I need this to be send back as a key (string) with []float64 value. This way I have an array of data associated with a key. Also, this needs to have a type. The best method I've found so far to accomplish this was to build put all of the data into a struct, encode it and send that back to the ResponseWriter.

I have seen several questions on making JSON from a database but I haven't found anything utilizing the struct method. I wrote the below code into a single function to illustrate my question. This is VERY limited in that it will only handle two fields and it MUST be a float64.

Therefore, my question is: How do I create this JSON from a query response that has the correct type before sending this back to the client and is there a way to do this dynamically (ie, can accept a variable number of columns and unknown types)?:

{ "Values":[12.54, 76.98, 34.90], "Dates": ["2017-02-03", "2017-02-04:, "2017-02-05"]}


    type DbDao struct{
      db *sql.DB
    }

    type JSONData struct {
      Values []float64
      Dates []string
    }


    func (d *DbDao) SendJSON(sqlString string, w http.ResponseWriter) (error) {

      stmt, err := d.db.Prepare(sqlString)
      if err != nil {
        return err
      }
      defer stmt.Close()

      rows, err := stmt.Query()
      if err != nil {
        return err
      }
      defer rows.Close()

      values := make([]interface{}, 2)
      scanArgs := make([]interface{}, 2)
      for i := range values {
        scanArgs[i] = &values[i]
      }

      for rows.Next() {
        err := rows.Scan(scanArgs...)
        if err != nil {
          return err
        }

        var tempDate string 
        var tempValue float64
        var myjson JSONData

        d, dok := values[0].([]byte)
        v, vok := values[1].(float64)

        if dok {
          tempDate = string(d)
          if err != nil {
            return err
          }
          myjson.Dates = append(myjson.Dates, tempDate)
        }

        if vok {      
          tempValue = v 
          myjson.Values = append(myjson.Values, tempValue)
          fmt.Println(v)
          fmt.Println(tempValue)

        }    

        err = json.NewEncoder(w).Encode(&myjson)
        if err != nil {
          return err
        }
      }

      return nil 
    }

  • 写回答

3条回答 默认 最新

  • dqm74406 2017-03-15 00:13
    关注

    This is the best implementation that I was able to come up with that would make it dynamic. It is also significantly shorter than my original. As I've seen this type of question quite a bit, I hope this helps others. I am open to other answers that have a better implementation of this:

    func (d *DbDao) makeStructJSON(queryText string, w http.ResponseWriter) error {
    
        // returns rows *sql.Rows
        rows, err := d.db.Query(queryText)
        if err != nil {
            return err
        }
        columns, err := rows.Columns()
        if err != nil {
            return err
        }
    
        count := len(columns)
        values := make([]interface{}, count)
        scanArgs := make([]interface{}, count)
        for i := range values {
            scanArgs[i] = &values[i]
        }
    
        masterData := make(map[string][]interface{})
    
        for rows.Next() {
            err := rows.Scan(scanArgs...)
            if err != nil {
                return err
            }
            for i, v := range values {
    
                x := v.([]byte)
    
                //NOTE: FROM THE GO BLOG: JSON and GO - 25 Jan 2011:
                // The json package uses map[string]interface{} and []interface{} values to store arbitrary JSON objects and arrays; it will happily unmarshal any valid JSON blob into a plain interface{} value. The default concrete Go types are:
                //
                // bool for JSON booleans,
                // float64 for JSON numbers,
                // string for JSON strings, and
                // nil for JSON null.
    
                if nx, ok := strconv.ParseFloat(string(x), 64); ok == nil {
                    masterData[columns[i]] = append(masterData[columns[i]], nx)
                } else if b, ok := strconv.ParseBool(string(x)); ok == nil {
                    masterData[columns[i]] = append(masterData[columns[i]], b)
                } else if "string" == fmt.Sprintf("%T", string(x)) {
                    masterData[columns[i]] = append(masterData[columns[i]], string(x))
                } else {
                    fmt.Printf("Failed on if for type %T of %v
    ", x, x)
                }
    
            }
        }
    
        w.Header().Set("Content-Type", "application/json")
    
        err = json.NewEncoder(w).Encode(masterData)
    
        if err != nil {
            return err
        }
        return err
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算