doushi4633 2017-07-19 15:35
浏览 24
已采纳

正确删除Go中的第二个json.Marshal

I have, for whatever reason, while trying to build a simple Rest API in Go with MySQL storage, added a second json.Marshal which is double-encoding and producing results with escaped quotes and such. I could strip the quotes, but I think I shouldn't have two json.Marshal things happening in the first place.

The problem is twofold - 1) which is proper to remove (leaning toward the first because "result" should be the larger array) and 2)how to keep the code functioning after removal? I can't just simply remove the first one as I start encountering all sorts of errors. Here are the relevant portions of the code:

type Volume struct {
    Id int
    Name string
    Description string
}

... skipping ahead ....

var result = make([]string,1000)
switch request.Method {
    case "GET":

        name  := request.URL.Query().Get("name")

        stmt, err := db.Prepare("select id, name, description from idm_assets.VOLUMES where name = ?")
            if err != nil{
                fmt.Print( err );
            }

            rows, err := stmt.Query(name)

            if err != nil {
                fmt.Print( err )
            }

            i := 0

            for rows.Next() {
                var name string
                var id int
                var description string
                err = rows.Scan( &id, &name, &description )
                if err != nil {
                    fmt.Println("Error scanning: " + err.Error())
                        return
                }
                volume := &Volume{Id: id,Name:name,Description: description}

Here is the first json.Marshal ...

                b, err := json.Marshal(volume)
                    fmt.Println(b)
                if err != nil {
                    fmt.Println(err)
                    return
                }
                result[i] = fmt.Sprintf("%s", string(b))
                i++
            }
        result = result[:i]

...skipping other cases for PUT, DELETE, Etc. To the second json.Marshal ...

default:
    }
json, err := json.Marshal(result)
if err != nil {
    fmt.Println(err)
    return
}
fmt.Fprintf(response,"'%v'
",string(json) )
  • 写回答

1条回答 默认 最新

  • duankanjian4642 2017-07-19 15:44
    关注

    Turn result into an array of *Volume

    result := []*Volume{}
    

    and then append new Volume records:

    result = append(result, &Volume{Id: id,Name:name,Description: description})
    

    and in the end use Marshal(result) to get the JSON result.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀