将Marshall JSON Slice转换为有效的JSON。

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

Marshall JSON Slice to valid JSON

问题

我正在使用Golang构建一个REST API,但在尝试正确地编组Json Slice时遇到了一些问题。我已经苦思冥想了一段时间,甚至在查看了几个问题和答案以及网上的资料后仍然没有解决。

基本上,我有一个称为Redis的客户端,在调用-X GET /todo/之后返回一个todos的切片。

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

现在,我想根据是否找到了todos来返回给定的Response,所以我有一个类似的Struct

  1. type Response struct {
  2. Status string
  3. Data []string
  4. }

然后,如果我找到了一些todos,我只需使用以下代码将其编组为json:

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

为了去除响应中不必要的\,我使用bytes.Replace,如下所示:

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

最后,得到的结果是:

  1. {
  2. "Status" : "Ok",
  3. "Data" : [
  4. "{\"content\":\"test6\",\"id\":\"46\"}",
  5. "{\"content\":\"test5\",\"id\":\"45\"}"
  6. ]
  7. }

正如你所看到的,每个{之前和每个}之后的"都是错误的,除了第一个和最后一个之外。
而正确的JSON应该是:

  1. {
  2. "Status": "Ok",
  3. "Data": [{
  4. "content": "test6",
  5. "id": "46"
  6. }, {
  7. "content": "test5",
  8. "id": "45"
  9. }]
  10. }

我成功地通过找到它们的索引并将其删除以及使用正则表达式来去除它们,但我想知道是否有一种更简洁和更好的方法来实现这一点?

英文:

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

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

  1. type Response struct {
  2. Status string
  3. Data []string
  4. }

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

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

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

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

Finally, getting

  1. {
  2. "Status" : "Ok",
  3. "Data" : [
  4. "{"content":"test6","id":"46"}",
  5. "{"content":"test5","id":"45"}"
  6. ]
  7. }

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

  1. {
  2. "Status": "Ok",
  3. "Data": [{
  4. "content ": "test6",
  5. "id ": "46"
  6. }, {
  7. "content ": "test5",
  8. "id ": "45"
  9. }]
  10. }

> 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

得分: 7

每当可能时,你应该从与你期望的 JSON 匹配的 Go 对象进行编组。我建议从 Redis 解析 JSON:

  1. type Response struct {
  2. Status string
  3. Data []*Info
  4. }
  5. type Info struct {
  6. Content string `json:"content"`
  7. ID string `json:"id"`
  8. }
  9. func main() {
  10. r := &Response{Status: "OK"}
  11. for _, d := range data {
  12. info := &Info{}
  13. json.Unmarshal([]byte(d), info)
  14. // 处理错误
  15. r.Data = append(r.Data, info)
  16. }
  17. dat, _ := json.Marshal(r)
  18. fmt.Println(string(dat))
  19. }

Playground 链接

英文:

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

  1. type Response struct {
  2. Status string
  3. Data []*Info
  4. }
  5. type Info struct {
  6. Content string `json:"content"`
  7. ID string `json:"id"`
  8. }
  9. func main() {
  10. r := &Response{Status: "OK"}
  11. for _, d := range data {
  12. info := &Info{}
  13. json.Unmarshal([]byte(d), info)
  14. //handle error
  15. r.Data = append(r.Data, info)
  16. }
  17. dat, _ := json.Marshal(r)
  18. fmt.Println(string(dat))
  19. }

Playground Link

huangapple
  • 本文由 发表于 2017年5月9日 04:42:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/43856948.html
匿名

发表评论

匿名网友

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

确定