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 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用