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

如何在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条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 Maya的Fbx模型导入Ue4.24后为什么个别部位的UV发生了改变?
      • ¥15 网页设计与开发html
      • ¥15 bin格式的程序文件烧录GD32F105芯片。起始地址填多少?
      • ¥15 python对txt文件的处理
      • ¥25 需要一个能在H5中实现扫码的插件
      • ¥50 ArcGIS或MATLAB实现批量计算整个tif图像的EVI
      • ¥20 两个板子之间CAN通信ID号怎么设置
      • ¥15 两个板子CAN通信的话ID号怎么设置
      • ¥15 vue使用element-ui的el-upload上传图片至服务器,服务端使用的是node.js,图片上传成功,但界面显示不出来,是跨域问题?
      • ¥15 ANSYS APDL循环结果输出