dongmacuo1193 2017-05-08 20:42 采纳率: 0%
浏览 99
已采纳

将Marshall JSON Slice转换为有效JSON

I'm building a REST API using Golang but I'm having some troubles trying to correctly Marshalling a Json Slice. I've been scratching my head for a while now, even after looking to several questions and answer and on the web.

Essentially, I have a Redis client that called after a call -X GET /todo/ spits up a slice of todos

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

Now, I want to return a given Response based on the fact that I found todos or not, so I have a Struct like

type Response struct {
    Status string
    Data []string
}

Then, If I found some todos I just Marshal a json with

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

And, In order to remove unnecessary \ inside the response, I use bytes.Replace like

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

Finally, getting

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

As you can see each " before each { and after each }, excluding the first and the last ones, are clearly wrong. While the correct JSON would be

{
    "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.

Is there a clean and better way to achieve that?

  • 写回答

1条回答 默认 最新

  • duanbi5906 2017-05-08 20:53
    关注

    Whenever possible you should marshal from go objects that match your desired json. I'd recommend parsing the json from redis:

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型