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

浦那:

从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.
 }]

这是用于检索上述数据的代码。struct是:

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

问题是数据在数组对象中供我使用,我需要{}如上所述的String结构数据我之前曾发布过此问题,但未获得任何成功答案。我从很多时候开始尝试,请帮助我。

sf9v:

根据OP讨论的内容,将结构编组Items将得到以下结果:

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

我考虑了两种方法:

  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
            }
    
            buffer.WriteString(string(b) + ",")
        }
    
        s := strings.TrimSpace(buffer.String())
        // trim last comma
        s = s[:len(s)-1]
    
        return s, nil
    }
    
  2. 或只是修剪前和后方括号:

    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
    }
    

链接到代码:https : //play.golang.org/p/F1SUYJZEn_n

编辑:由于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
}

链接到新代码:https : //play.golang.org/p/dVvsQlsRqZO

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在golang中将动态生成的数组对象数据转换为JSON格式的字符串?

将数据框转换为rec数组(并将对象转换为字符串)

如何将字符串数据转换为json格式的数据

将数据格式从字符串数组转换为数字

jQuery将对象数据转换为字符串数组

如何将格式化为数组变量的字符串转换为javascript对象?

通过应用一些字符串格式将数据框的字符串(对象)列转换为数字

将(csv)字符串对象转换为数据框

将数据数组转换为字符串

如何将字符串数组转换为对象

如何将字符串转换为对象数组?

如何将字符串转换为对象数组

我如何将数据表日期转换为某种字符串格式

如何将数字数据框列转换为格式字符串

如何将类似数据的数组从字符串转换为二维数组?

如何使用非标准格式将字符串转换为 .Net DateTime 对象?

如何使用Golang将字符串转换为XML

如何将 NodeJS 表单数据对象转换为 JSON 字符串

R:如何将字符串数据帧转换为POSIXt对象?

如何将熊猫对象而不是整个数据框转换为字符串?

如何将字符串转换为JSON并将数据保存在数组中?

如何将RDD数组字符串转换为数据帧

Angular /如何将获取的数据从字符串转换为数组

使用PHP将SQL数据转换为字符串

使用 javascript 或 c# 将 JSON 字符串转换为数据数组

如何将格式正确的 Javascript 对象(字符串格式)转换为对象?

如何使用键值对将字符串转换为对象

如何使用GSON / JSON将字符串数组转换为对象?

将字符串格式的数组转换为javascript数组