gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:42:12 24 4
gpt4 key购买 nike

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

[{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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com