On the data retrieval the data is in the form of array object like this:
[{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.}]
how will I change it in JSON. I just need to break the array object braces [].
I have tried to Marshal
it. But It gives me like:
[{"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."}]
The code I'd tried
Struct
type Item struct {
Id int `json:"id"`
Category string `json:"category"`
Name string `json:"name"`
Description string `json:"description"`
}
type Items []Item
Here the function for retrieving data
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))
}
I want to make the output like
{"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."}
can anyone help me I tried it lot of times but don't take any success.
See Question&Answers more detail:
os