我正在使用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
一个带有
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"
}]
}
我成功设法通过找到他们的索引并将其修剪掉来解决问题 还有正则表达式,但我很想知道。
是否有更干净,更好的方法来实现这一目标?
答案 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))
}