Marshall JSON 切片有效 JSON

Marshall JSON Slice to valid JSON

我正在使用 Golang 构建 REST API,但我在尝试正确编组 Json 切片时遇到了一些麻烦。即使在网上看了几个问题和答案之后,我也摸不着头脑了一段时间。

本质上,我有一个 Redis 客户端,它在调用 -X GET /todo/ 后调用了 todos

[{"content":"test6","id":"46"} {"content":"test5","id":"45"}] //[]string

现在,我想 return 一个给定的 Response 基于我发现 todos 或没有的事实,所以我有一个 Struct 喜欢

type Response struct {
    Status string
    Data []string
}

然后,如果我找到一些 todos 我只是 Marshal 一个 json 和

if(len(todos) > 0){
    res := SliceResponse{"Ok", todos}
    response, _ = json.Marshal(res)
}

而且,为了删除响应中不必要的 \,我使用 bytes.Replace like

response = bytes.Replace(response, []byte("\"), []byte(""), -1)

终于得到

{
   "Status" : "Ok",
   "Data" : [
              "{"content":"test6","id":"46"}",
              "{"content":"test5","id":"45"}"
    ]
}

如你所见,每个 { 之前和每个 } 之后的每个 ",除了第一个和最后一个,显然是错误的。 而正确的 JSON 应该是

{
    "Status": "Ok",
    "Data": [{
        "content ": "test6",
        "id ": "46"
    }, {
        "content ": "test5",
        "id ": "45"
    }]
}

I successfully managed to get them off by finding their index and trim them off and also with regex but I was wondering.

有没有更干净、更好的方法来实现它?

只要有可能,您应该从符合您所需 json 的 go 对象中编组。我建议从 redis 解析 json:

type Response struct {
    Status string
    Data   []*Info
}

type Info struct {
    Content string `json:"content"`
    ID      string `json:"id"`
}

func main() {
    r := &Response{Status: "OK"}
    for _, d := range data {
        info := &Info{}
        json.Unmarshal([]byte(d), info)
        //handle error
        r.Data = append(r.Data, info)
    }
    dat, _ := json.Marshal(r)
    fmt.Println(string(dat))
}

Playground Link