Mongodb 如何使用golang将数组对象数据转换为字符串格式数据?

Mongodb 如何使用golang将数组对象数据转换为字符串格式数据?,mongodb,go,Mongodb,Go,有一个从mongodb检索的数组对象。数据如下所示:- [{ 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. }] 这是用于检索上述数据的

有一个从mongodb检索的数组对象。数据如下所示:-

[{
  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.
 }]
这是用于检索上述数据的代码 结构是:

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

func GetData(Query interface{}) (result Items, err error) {
    mongoSession := ConnectDb()
    sessionCopy := mongoSession.Copy()
    defer sessionCopy.Close()
    getCollection := mongoSession.DB("custom").C("custom")
    err = getCollection.Find(Query).All(&result)
    if err != nil {
        return result, err
    }
    return result, nil
}
/*
 *  Retrieve the data used by main function
 */
func retrieve(c *gin.Context) {
  //mongoSession := ConnectDb()
  conditions := bson.M{}
  data, err :=GetData(conditions)
  if err != nil {
    fmt.Println("There is somthing wrong")
  }
  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))
}
运行
json.Marshal
,输出如下所示:

[{
  "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."
}]
预期产量

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

问题是数据在数组对象中供我使用,我需要
{}
之间的字符串结构数据,如上所示。我以前发布过这个问题,但没有得到任何成功的答案。我一直在尝试帮助我,谢谢。

根据OP所讨论的内容,封送结构
项将得到以下结果:

[{
  "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."
}]
从中,OP希望得到一个如下所示的字符串:

{
  "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 getMyString2(items Items) (string, error) {
    
        b, err := json.Marshal(items)
        if err != nil {
            return "", err
        }
    
        s := string(b)
        s = strings.TrimSpace(s)
        // trim leading and trailing spaces
        s = s[1 : len(s)-1]
        return s, nil
    }
    
  • 链接到代码:

    编辑:因为OP希望它是空间分隔的,所以我修改了方法1以满足要求:

    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
            }
            // use space to separate each json string in the array
            buffer.WriteString(string(b) + " ")
        }
    
        s := strings.TrimSpace(buffer.String())
    
        return s, nil
    }
    

    链接到新代码:

    Hi@Puneet,您的预期输出是什么?另外,您所说的从mongodb检索到的数据对我来说是无效的。@srf那么我该怎么做呢?帮我一下,我是刚到golang的。你能帮我吗?我会尽我最大的努力,你能描述一下你的用例吗?可能的重复没有理由发布你的问题两次。如果你想澄清一些事情,请编辑你现有的问题。先生,每件事都是令人惊讶的,但有一件事给我带来了错误,那就是字符串被逗号分隔了,它可能是一个空格。请参见
    }
    pranthese后面的逗号
    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
            }
            // use space to separate each json string in the array
            buffer.WriteString(string(b) + " ")
        }
    
        s := strings.TrimSpace(buffer.String())
    
        return s, nil
    }