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

标签 go

在数据检索中,数据是这样的数组对象的形式:

[{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 它。但它给我这样的感觉:

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

我试过的代码

结构

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

这里是检索数据的函数

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))
}

我想让输出像

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

任何人都可以帮助我,我尝试了很多次,但没有成功。

最佳答案

简单地单独编码 slice 的每个元素:

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)
                }
        }
}

关于go - golang中如何将动态生成的数组对象数据转换成JSON格式的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49669922/

相关文章:

function - 以矩阵接口(interface)为参数的Go函数

go - 通过 GoCQL 在 ScyllaDB 上进行阻塞/一致/可预测的回复/请求

json - 如何在不嵌入的情况下将 JSON 解码添加到外部库类型

go - 在 go 中构建一个完整的 HTTP 反向代理需要什么?

go - 具有多个 UI 的工具的项目结构

go - 写入两个独立的 channel 是否可靠地顺序进行?

go - 防止Golang后台进程过度使用CPU

Golang channel 处理发送!=接收

Golang 模板 : what is in the context?

go - fmt软件包中的不同打印功能之间有什么区别?