在数据检索中,数据采用数组对象的形式,如下所示:

1
[{1 fruits Apple Apple is my favorite fruit.} {2 colors Red Red color is always charming.} {3 flowers Lotus It is one of the most beautiful flowers in this world.}]

如何在JSON中更改它。我只需要打破数组对象括号[]。

我尝试Marshal。但是它给我的像是:

1
[{"id":1,"category":"fruits","name":"Apple","description":"Apple is my favorite fruit."},{"id":2,"category":"colors","name":"Red","description":"Red color is always charming."},{"id":3,"category":"flowers","name":"Lotus","description":"It is one of the most beautiful flowers in this world."}]

我尝试过的代码

结构

1
2
3
4
5
6
7
type Item struct {
 Id          int    `json:"id"`
 Category    string `json:"category"`
 Name        string `json:"name"`
 Description string `json:"description"`
}
type Items []Item

这里是检索数据的功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
func GetData(productQuery interface{}) (result Items, err error) {
 mongoSession := ConnectDb()
 sessionCopy := mongoSession.Copy()
 defer sessionCopy.Close()
 getCollection := mongoSession.DB("custom").C("custom")
 err = getCollection.Find(productQuery).Select(bson.M{"password": 0}).All(&result) //.Skip(skip).Limit(limit)
 if err != nil {
    return result, err
 }
 return result, nil
}
/*
 *
 *  Retrieve the data used by main function
 *
 *
 */

func retrieve(c *gin.Context) {
  conditions := bson.M{}
  data, err :=GetData(conditions)
  if err != nil {
    fmt.Println("There is somthing wrong")
  }
  fmt.Println("--------------------")
  fmt.Println(data)
  fmt.Println("--------------------")
  arrange(data)
  return
}  

func arrange(data Items) {
  pagesJson, err := json.Marshal(data)
  if err != nil {
      log.Fatal("Cannot encode to JSON", err)
  }
  fmt.Println(string(pagesJson))
}

我想使输出像

1
{"id": 1,"category":"fruits","name":"Apple","description":"Apple is my favorite fruit."} {"id": 2,"category":"colors","name":"Red",description":"Red color is always charming."} {"id": 3,"category":"flowers","name":"Lotus","description":"It is one of the most beautiful flowers in this world."}

有人可以帮我吗,我尝试了很多次,但没有成功。

  • {1 fruits Apple Apple is my favorite fruit.}是无效的JSON,因此您不能期望使用json包来解析或生成它。
  • thanku答复,但我编辑了我的问题
  • 显然,迭代切片并封送每个元素。
  • 我是golang的新手,请为我解释一下吗?
  • 1.创建一个可以封送json数组元素(例如type struct T)的结构2.在[] T中封送json 3.现在只需遍历切片并根据需要进行打印
  • 您想要的最终结果不是有效的json,您知道吗?您是否需要json格式的结果?
  • 是的,先生,我需要json格式的结果
  • 有没有什么方法可以解决这个问题?

此代码将起作用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main

import (
 "bytes"
 "encoding/json"
 "fmt"
 "log"
 "strings"
)

type Item struct {
  Id          int    `json:"id"`
  Category    string `json:"category"`
  Name        string `json:"name"`
  Description string `json:"description"`
}

type Items []Item

var myJson = []byte(`[{
"id":1,
"category":"fruits",
"name":"Apple",
"description":"Apple is my favorite fruit."
},
{
"id":2,
"category":"colors",
"name":"Red",
"description":"Red color is always charming."
},
{
"id":3,
"category":"flowers",
"name":"Lotus",
"description":"It is one of the most beautiful flowers in this world."
}]`)

func main() {
    var items Items

    err := json.Unmarshal(myJson, &items)
    if err != nil {
     log.Fatal(err)
    }

    s, err := getMyString(items)
   if err != nil {
        log.Fatal(err)
   }

   fmt.Println(s)
}

func getMyString(items Items) (string, error) {
  var buffer bytes.Buffer
  var err error
  var b []byte

  for _, item := range items {
    b, err = json.Marshal(item)
    if err != nil {
        return"", err
    }

    buffer.WriteString(string(b) +"")
  }

  s := strings.TrimSpace(buffer.String())

  return s, nil
}

简单地分别对切片的每个元素进行编码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import (
       "encoding/json"
       "log"
       "os"
)

type T struct {
        ID          int    `json:"id"`
        Category    string `json:"category"`
        Name        string `json:"name"`
        Description string `json:"description"`
}

func main() {
        var data []T

        enc := json.NewEncoder(os.Stdout)
        for _, x := range data {
                if err := enc.Encode(x); err != nil {
                        log.Fatal(err)
                }
        }
}
  • 我检索的数据是接口的类型。它给我错误cannot range over data (type interface {})
  • 如果以后要使用它,请不要将数据存储在空接口{}中。由于您尚未显示如何检索它,因此我无法为您提供帮助。
  • 您检索的数据不是interface {}类型,而是Items类型。将func arrange(data interface{})更改为func arrange(data Items)
  • 我更改了它,但是问题是一样的:(。我从一天半开始尝试它:(
  • 你能帮助我吗 ?
  • @Puneet,我不知道还能告诉你什么。如果您还没有这样做,请参加环游。也许那会清除一切。