Marshall JSON切片有效JSON

时间:2017-05-08 20:42:29

标签: json go marshalling

我正在使用Golang构建REST API,但是我在尝试正确编组Json Slice方面遇到了一些麻烦。我现在已经摸不着头脑了,即使在看了几个问题并回答并在网上之后。

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

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

现在,我想根据我发现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之类的

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"
    }]
}
  

我成功设法通过找到他们的索引并将其修剪掉来解决问题   还有正则表达式,但我很想知道。

是否有更干净,更好的方法来实现这一目标?

1 个答案:

答案 0 :(得分:3)

只要有可能,你应该使用符合你想要的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