正确地在Go中移除第二个json.Marshal。

huangapple go评论95阅读模式
英文:

Correctly remove second json.Marshal in Go

问题

我在尝试使用Go和MySQL存储构建一个简单的Rest API时,由于某种原因,我添加了第二个json.Marshal,这导致双重编码,并产生了带有转义引号等结果。我可以去掉引号,但我认为我一开始就不应该有两个json.Marshal。

问题有两个方面 - 1)应该删除哪个(倾向于删除第一个,因为"result"应该是较大的数组),以及2)如何在删除后保持代码的功能性?我不能简单地删除第一个,因为我开始遇到各种错误。以下是代码的相关部分:

type Volume struct {
    Id int
    Name string
    Description string
}

... 省略部分代码 ....

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}

            // 这是第一个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]
        ... 省略其他PUTDELETE等情况到第二个json.Marshal ...

    default:
}

json, err := json.Marshal(result)
if err != nil {
    fmt.Println(err)
    return
}
fmt.Fprintf(response,"'%v'\n",string(json))

希望这可以帮助你解决问题。

英文:

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'\n",string(json) )

答案1

得分: 2

result转换为*Volume的数组

result := []*Volume{}

然后追加新的Volume记录:

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

最后使用Marshal(result)获取JSON结果。

英文:

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.

huangapple
  • 本文由 发表于 2017年7月19日 23:35:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/45195127.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定